I put together this simplified version of my code to demonstrate the issue:
public static void main(String []args){
String content="1 [thing i want]\n" +
"2 [thing i dont want]\n" +
"3 [thing i dont want] [thing i want]\n" +
"4 // [thing i want]\n" +
"5 [thing i want] // [thing i want]\n";
String BASE_REGEX = "(?!//)\\[%s\\]";
Pattern myRegex = Pattern.compile(String.format(BASE_REGEX, "thing i want"));
Matcher m= myRegex.matcher(content);
System.out.println("match? "+m);
String newContent = m.replaceAll("best thing ever");
System.out.println("regex "+myRegex);
System.out.println("content:\n"+content);
System.out.println("new content:\n"+newContent);
}
I expect my output to be:
new content:
1 best thing ever
2 [thing i dont want]
3 [thing i dont want] best thing ever
4 // [thing i want]
5 best thing ever // [thing i want]
but I see:
new content:
1 best thing ever
2 [thing i dont want]
3 [thing i dont want] best thing ever
4 // best thing ever
5 best thing ever // best thing ever
How do I fix the regex?
The unmodified string:
content:
1 [thing i want]
2 [thing i dont want]
3 [thing i dont want] [thing i want]
4 // [thing i want]
5 [thing i want] // [thing i want]
(?!//)is always true as the next consumed char is[. You seem to avoid replacing in single line comments, right? Match those comments, and only replace the matches in other contexts.contentas it exists if printed ?