简体   繁体   中英

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>

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM