Hi I am trying to understand Java regex replacement. I have lots of regex and replacement to apply on text in a file. I want to read regex and apply replacement on text.
Like, I want to replace text to variable in following example.
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");
}
}
}
But I get output as
text
variable text
Can any one explain how does group and replacement works in java? How to get correct output?
textwithvariablein your string, you don't need regex. If you want to do more than that, then show the real code.texttovariable. But it is not happening like that. What is correct regex ?