Reputation: 4338
I want to replace a substring that matches a pattern, only if it does not match a different pattern. For example, in the code shown below, I want to replace all '%s' but leave ':%s' untouched.
String template1 = "Hello:%s";
String template2 = "Hello%s";
String regex = "[%s&&^[:%s]]";
String str = template1.replaceAll(regex, "");
System.out.println(str);
str = template2.replaceAll(regex, "");
System.out.println(str);
The output should be:
Hello:%s
Hello
I am missing something in my regex. Any clues? Thanks!
Upvotes: 1
Views: 2204
Reputation: 37833
Use a negative lookbehind to achieve your goal:
String regex = "(?<!:)%s";
It matches %s
only if there is not a :
right before it.
Upvotes: 7