0

I have a requirement where I get a string in which I have to replace the value between

< p811:Credential> and   < /p811:Credential>

In this case AAAAA/BBBBBB)

Only the Credential text will be constant all the time the prefix will need not be the same

Example strings

1.abc < p811:Credential>AAAAA/BBBBBB< /p811:Credential>xyz
2.gsd< K999:Credential>EEEEE/XXXXX< / K999:Credential>tre

How can we do this ?

2 Answers2

2

For solving your specific problem , you can give this code:

line=" gsd< K999:Credential>EEEEE/XXXXX< / K999:Credential>tre";
String REGEX="(?<=Credential\\W?>)(\\w|\\d|/)*(?=<\\W?/\\W?(\\w|\\d)+:Credential\\W?>)";

line = line.replaceAll(REGEX, word_to_replace);
System.out.println(line);
Sujith PS
  • 4,776
  • 3
  • 34
  • 61
  • I am sorry not to mention this,p811 will need not to be same always i.e it can be like this aswell gsd< K999:Credential>EEEEE/XXXXX< / K999:Credential>tre – Satish Uppalapati Jan 08 '14 at 05:56
  • Can you give sample acceptable inputs and unacceptable inputs ? – Sujith PS Jan 08 '14 at 05:58
  • String replacement="< p811:Credential>"+replaceWord+"< /p811:Credential>"; how do you replace this if we have string like this gsd< K999:Credential>EEEEE/XXXXX< / K999:Credential>tre – Satish Uppalapati Jan 08 '14 at 10:26
  • the trouble with this solution is it will match `foo` – Bohemian Jan 08 '14 at 10:55
  • @Bohemian : I given 2nd solution to solve his specific problem. NO the 2nd solution will not match foo for sure. Why I given specific code because of the error : http://stackoverflow.com/questions/20706793/regex-java-look-behind-group-does-not-have-an-obvious-maximum-length-near – Sujith PS Jan 08 '14 at 11:00
  • @Bohemian : I edited my answer . Thank you for you comment. Now it will work. – Sujith PS Jan 08 '14 at 11:03
0
String search = "abc < p811:Credential>AAAAA/BBBBBB< /p811:Credential>xyz";

String regex = "(^.*?< ?[a-zA-Z0-9]{4}:Credential>)(.*?)(< ?/ ?[a-zA-Z0-9]{4}:Credential>.*?$)";
String replacement = "$1Replacement Text$3";

String result = search.replaceAll(regex, replacement);

I put 3 capture groups in the regex:

  • .........< XXXX:Credential>
  • >XXXX/XXXXX<
  • < / XXXX:Credential>.........

Then simply put an easy replacement text, which uses backreferences $1 and $3 to preserve the characters to the left and right of your desired match.

Vasili Syrakis
  • 9,321
  • 1
  • 39
  • 56