我使用正则表达式和字符串replaceFirst替换以下模式.
String xml = "otpcode=1234567password=abc123";
if(xml.contains("otpcode")){
Pattern regex = Pattern.compile("otpcode=(.*)");
Matcher matcher = regex.matcher(xml);
if (matcher.find()) {
xml = xml.replaceFirst("otpcode=" + matcher.group(1)+ "","otpcode=xxxx");
}
}
System.out.println(xml);
if (xml.contains("password")) {
Pattern regex = Pattern.compile("password=(.*)");
Matcher matcher = regex.matcher(xml);
if (matcher.find()) {
xml = xml.replaceFirst("password=" + matcher.group(1)+ "","password=xxxx");
}
}
System.out.println(xml);
期望的O / p
otpcode=xxxxpassword=abc123
otpcode=xxxxpassword=xxxx
实际的输出/输出(在第一个IF本身中一次替换整个字符串)
otpcode=xxxx
otpcode=xxxx