Reputation: 335
I'm new to Regex but I think my problem should be solved using it. Basically, I want to replace whitespace in a string with "dog", as long as the words "cat" or "bird" or "dog" aren't before or after.
Example:
Good Dog = Good Dog
Large Brown = Large Dog Brown
Cat Ugly = Cat Ugly
So only the second string would be modified. I can handle something like this easily string replace etc, but i'm curious to know if this should be done in regex.
Upvotes: 2
Views: 101
Reputation: 124225
You are looking for lookaround mechanisms. Your code can look more or less like
yourString = yourString.replaceAll("(?<!cat|bird|dog)\\s(?!cat|bird|dog)"," dog ")
// ^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^
// negative look-behind negative look-ahead
You can improve this regex by making it case insensitive with (?i)
flag.
You can also add word boundaries (\b
) to make sure you are matching whole words, and not only its parts like cataclysm
.
Demo (I also used non-capturing group (?:...)
to increase performance a little):
String[] data ={ "Good Dog", "Large Brown", "Cat Ugly"};
for (String s : data){
System.out.println(s.replaceAll("(?i)(?<!\\b(?:cat|bird|dog)\\b)\\s(?!\\b(?:cat|bird|dog)\\b)"," dog "));
}
Output:
Good Dog
Large dog Brown
Cat Ugly
Upvotes: 4