Search code examples
javaregexreplaceall

Java Regex - How to replace a pattern starts with and ends with


I have 2 Scenarios:

  1. String Starts with Sample Country ! i.e. Sample Country ! Test Data

I want a regex to replace Sample Country ! with Empty String, Country here is not fixed, it can be US, France etc

I tried:

System.out.println(str.replaceAll("^(Sample[^!]+!)", ""));

I am getting the Output

! Test Data 

whereas I just want

Test Data
  1. String ends with Sample Country ! i.e. Test Data Sample Country ! here also I just want

    Test Data

Can someone help to provide the correct Regular expression with the explanation. Thanks a lot


Solution

  • Try this regex here:

    String[] testcases = new String[] {
        "Sample foo ! Test Data", 
        "Sample bar ! Test Data", 
        "Test Data Sample foo !", 
        "Test Data Sample bar !"
    };
    
    for (String str : testcases) {
        System.out.println(str.replaceAll("(.* ?)(Sample[a-zA-Z ]+ ! ?)(.*)", "$1$3"));
    }
    

    Explanation:

    (.* ?) // first match group, matches anything, followed by an optional space
    
    (Sample[a-zA-Z ]+ ! ?) // second match group, matches the String "Sample followed by a series of letters (your country), a whitespace, an exclamation mark and an optional space
    
    (.*) // third match group, matches anything
    

    So the second match group ($2) will contain your "Sample Country" string and we can just replace the result with only the first ($1) and the third ($3) match group.