3

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>

1 Answer 1

4

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...

Sign up to request clarification or add additional context in comments.

1 Comment

@jackk - Verified the answer and found as expected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.