I’m trying to improve a regular expression.
I have this string:
String myString =
"stuffIDontWant$KEYWORD$stuffIWant$stuffIWant$KEYWORD$stuffIDontWant";
And I made this to substract only the stuff I want:
String regex = "\\$KEYWORD\\$.+\\$.+\\$KEYWORD\\$";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(myString);
if(m.find()){
String result = stuff.substring(m.start(), m.end());
}
The goal is to get stuffIWant$stuffIWant and then split it with the character $, so, looking to improve it and avoid to import Patter and Matcher to my java source, I read about lookarounds, so my second approach is:
//Deletes what matches regex
myString.replaceAll(regex, "");
// Does nothing, and i thought it was just the opposite of the above instruction.
myString.replaceAll("(?! "+regex+")", "");
What is the correct way and where is my concept wrong?
You’re getting there! But most would use capture groups.
These parentheses will store what they enclose, i.e. capture. The first set will be indexed 1, the second set will be indexed 2. You can try this with the above expression to see what’s happening.
It is possible to solve with lookarounds too, but unnecessary: