I have 2 Scenarios:
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
String ends with Sample Country ! ie 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
Edit :
let's make a better way. you will have not only 2 cases you will have 3 cases
(pattern + data) ---> ^Sample[^!]+! (pattern) ([^!]) (data)
( data +pattern) ---> ([^!]) (data) Sample[^!]+!$ (pattern)
(pattern + data + pattern) ---> (^Sample[^!]+! (pattern) ([^!]) (data) Sample[^!]+!$ (pattern)
so we have to check all the cases in our string with regex. we need OR cases in regex it is "|" another thing is we have to avoid not matched cases must be ignored it is with (?:(regex)) descripted here
public class HelloWorld {
public static void main(String[] args) {
String[] testcases = new String[] {
"Sample foo ! Test1 Data",
"Sample bar ! Test2 Data",
"Test3 Data Sample foo !",
"Test4 Data Sample bar !",
"Sample bar ! Test5 Data Sample bar !"
};
for (String str: testcases) {
System.out.println(str.replaceAll("(?:(^Sample[^!]+!([^!])))|(?:(([^!])Sample[^!]+!$))|(?:(^Sample[^!]+!([^!]))Sample[^!]+!$)", "$2$4").trim());
}
}
} we used your regex and make a new regex after grouping data will be at ($2,$4) groups because of that we replace the string with 2nd and 4th group values. I hope this will help. compile code online
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.