在java中查找并替换字符串模式
我使用regex和stringreplacefirst替换模式,如下所示在java中查找并替换字符串模式,java,regex,string,Java,Regex,String,我使用regex和stringreplacefirst替换模式,如下所示 String xml = "<param>otpcode=1234567</param><param>password=abc123</param>"; if(xml.contains("otpcode")){ Pattern regex = Pattern.compile("<param>otpcode=(.*)</param>");
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);
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(“密码”)){
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
<param>otpcode=xxxx</param><param>password=abc123</param>
<param>otpcode=xxxx</param><param>password=xxxx</param>
otpcode=xxxxpassword=abc123
otpcode=xxxxpassword=xxxx
实际o/p(在第一次放炮中替换整个字符串(如果其本身)
otpcode=xxxx
otpcode=xxxx
您需要执行非贪婪正则表达式:
<param>otpcode=(.*?)</param>
<param>password=(.*?)</param>
otpcode=(*?)
密码=(*)
这将匹配到第一个
而不是最后一个…@jackk-验证了答案并按预期找到。
<param>otpcode=(.*?)</param>
<param>password=(.*?)</param>