Reputation: 711
First and foremost, this is not a homework/school question. This is something I needed for a personal project and was able to generalize the problem using simple characters as follows:
Create a regular expression which can be used in the java string replaceAll function for an input string aaabaabaa (or similar) and converts each a to A, UNLESS it is preceded by a b. So the expected output is AAAbaAbaA. I've been trying this for at least 2 hours now... The best I could come up with was:
replaceAll("^a|([^b])a", "$1A");
This fails on aaa, where the return value is AaA
I'm trying to say "Any 'a' without a 'b' before it should be an A. Any ideas for a RegEx novice? Thanks very much!
Upvotes: 0
Views: 67
Reputation: 149050
Try using a negative lookbehind:
str.replaceAll("(?<!b)a", "A");
This will match any a
not immediately preceded by a b
.
Upvotes: 3