我使用正则表达式和字符串 replaceFirst 来替换以下模式。
实际输出(在第一个IF语句中一次性替换整个字符串)
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);
期望的输出结果
<param>otpcode=xxxx</param><param>password=abc123</param>
<param>otpcode=xxxx</param><param>password=xxxx</param>
实际输出(在第一个IF语句中一次性替换整个字符串)
<param>otpcode=xxxx</param>
<param>otpcode=xxxx</param>