RedGuts
RedGuts

Reputation: 83

Find and Replace a pattern of string in java

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

Answers (1)

brso05
brso05

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

Related Questions