Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/379.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中查找并替换字符串模式_Java_Regex_String - Fatal编程技术网

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

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

我使用regex和stringreplacefirst替换模式,如下所示

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>