2014-04-11 3 views
1

사이에 문자열을 대체 내가 문자열로 다음 XML 조각이 있습니다자바 - 찾아 두 패턴 문자열

String str ="<xs:user>userName</xs:user><xs:password>userPassword</xs:password> 
<xs:address>addressString</xs:address>"; 

어떤 것 XXXXXXX에있는 userPassword를 대체 할 수있는 가장 좋은 방법은?

편집 : xs (네임 스페이스)는 다를 수 있습니다. 이 사용

+1

경계/특수한 경우 : 암호에

답변

1

봅니다 :

String str2 = str.replaceFirst("<xs:password>.*?</xs:password>", "<xs:password>xxxxxxxxxx</xs:password>");` 
+0

여기서 욕심 많은'. *'을 사용하지 않고'. *? '로 바꾸십시오. – Joffrey

+0

예 좋은 조언 .. 편집 됨 – anirudh

1

이 그것을해야한다. 이것은 제가 지금 생각할 수있는 가장 간단한 해결책입니다.

public static void main(String[] args) { 
    String str = "aaaaa<xs:password>userPassword</xs:password>bbbbbbbbbb"; 
    String newPassword = "test"; 
    String s2 = str.replaceAll("<xs:password>[^<]*</xs:password>", "<xs:password>" + newPassword + "</xs:password>"); 
    System.out.println(s2); 
} 
+0

중첩 된 태그를 제외하므로 @anirudh 버전을 선호합니다. generalized, 여기 일을하고있다하더라도. – Joffrey

+0

+1 작동하는 해결책을 위해. – Joffrey

0

oldschool 기어-을 통해 - 더 - 문자열 approch은 다음과 같습니다 자바에서

String in = 
      "<xs:user>userName</xs:user>" + 
      "<xs:password>userPassword</xs:password>" + 
      "<xs:address>addressString</xs:address>"; 

    int pwStart = in.indexOf("<xs:password>") + 13; 
    int pwLen = in.indexOf("</xs:password>") - pwStart; 

    StringBuilder out = new StringBuilder(); 

    out.append(in.substring(0, in.indexOf("<xs:password>") + 13)); 
    for (int i = 0; i < pwLen; i++) { 
     out.append("x"); 
    } 
    out.append(in.substring(in.indexOf("</xs:password>"))); 

    System.out.printf("%s\n", in); 
    System.out.printf("%s\n", out); 
0

:이 도움이

public static void replace(){ 

    String str = 
      "<xs:user>userName</xs:user>" + 
      "<xs:password>userPassword</xs:password>" + 
      "<xs:address>addressString</xs:address>"; 

    String[] s = str.split("><"); 

    String[] t = s[1].split("password>"); 

    String[] a = t[1].split("</xs:"); 

    System.out.println(a[0]); 

    String newS = s[0] + "><" + t[0] + "password>" + "YOUR XXXXXXX GOES HERE" + "</xs:" + a[1] + "><" + s[2]; 

    System.out.println(newS); 

} 

희망을.