Reputation: 83
I use regex and string replaceFirst to replace the patterns as below.
String xml = "<param>otpcode=1234567</param><param>password=abc123</param>";
if(xml.contains("otpcode")){
Pattern regex = Pattern.compile("<param>otpcode=(.*)</param>");
Matcher matcher = regex.matcher(xml);
if (matcher.find()) {
xml = xml.replaceFirst("<param>otpcode=" + matcher.group(1)+ "</param>","<param>otpcode=xxxx</param>");
}
}
System.out.println(xml);
if (xml.contains("password")) {
Pattern regex = Pattern.compile("<param>password=(.*)</param>");
Matcher matcher = regex.matcher(xml);
if (matcher.find()) {
xml = xml.replaceFirst("<param>password=" + matcher.group(1)+ "</param>","<param>password=xxxx</param>");
}
}
System.out.println(xml);
Desired O/p
<param>otpcode=xxxx</param><param>password=abc123</param>
<param>otpcode=xxxx</param><param>password=xxxx</param>
Actual o/p (Replaces the entire string in a single shot in first IF itself)
<param>otpcode=xxxx</param>
<param>otpcode=xxxx</param>
Upvotes: 3
Views: 228
Reputation: 13222
You need to do a non-greedy regex:
<param>otpcode=(.*?)</param>
<param>password=(.*?)</param>
This will match up to the first </param>
not the last one...
Upvotes: 4