Java正则表达式和替换

提问

嗨,我试图了解Java正则表达式替换.我有很多正则表达式和替换内容可应用于文件中的文本.我想阅读正则表达式并在文本上应用替换.
在下面的示例中,我想将文本替换为变量.

import java.util.regex.*;
public class regex1{
public static void main(String args[]){
    String s1 = "cat catches dog text";
    Pattern p1 = Pattern.compile("\\s*cat\\s+catches\\s*dog\\s+(\\S+)");
    Matcher m1 = p1.matcher(s1);
    if (m1.find()){
        System.out.println(m1.group(1));
        s1 = m1.replaceFirst("variable $1");
        System.out.println(s1);
    }
    else{
        System.out.println("Else");
    }
}    
}

但是我得到的输出为

text
variable text

谁能解释java中的分组和替换工作原理?如何获得正确的输出?

最佳答案

尝试这个

import java.util.regex.*;
public class regex1{
public static void main(String args[]){
    String s1 = "cat catches dog text";
    Pattern p1 = Pattern.compile("\\s*cat\\s+catches\\s*dog\\s+(\\S+)");
    Matcher m1 = p1.matcher(s1);
    if (m1.find()){
        System.out.println(m1.group(1));
        s1 = s1.replaceFirst(m1.group(1),"variable");
        System.out.println(s1);
    }
    else{
        System.out.println("Else");
    }
}
}