Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex and replacement

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?

like image 325
Netro Avatar asked Dec 07 '25 00:12

Netro


2 Answers

Use this code:

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()){
    s1 = m1.replaceFirst(s1.substring(0, m1.start(1)) + "variable");
}
else{
    System.out.println("Else");
}
System.out.println(s1);
// cat catches dog variable
like image 131
anubhava Avatar answered Dec 08 '25 13:12

anubhava


Try this

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");
    }
}
}
like image 22
Ruchira Gayan Ranaweera Avatar answered Dec 08 '25 13:12

Ruchira Gayan Ranaweera



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!