Find and replace string pattern in java
I am using regex and string replaceFirst to replace patterns like 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 line with one shot at the very first IF)
<param>otpcode=xxxx</param>
<param>otpcode=xxxx</param>
+3
source to share