在java中查找并替换字符串模式

时间:2015-07-13 14:27:59

标签: java regex string

我使用正则表达式和字符串replaceFirst来替换下面的模式。

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);

所需的O / p

<param>otpcode=xxxx</param><param>password=abc123</param>
<param>otpcode=xxxx</param><param>password=xxxx</param>

实际o / p(在第一个IF本身的单个镜头中替换整个字符串)

<param>otpcode=xxxx</param>
<param>otpcode=xxxx</param>

1 个答案:

答案 0 :(得分:4)

你需要做一个非贪婪的正则表达式:

<param>otpcode=(.*?)</param>
<param>password=(.*?)</param>

这将匹配第一个</param>而非最后一个......