Search code examples
javaregexidentifier

Replacement specific identifer with regex


I have a java regex for replacing all instances of a specific identifier in a script.

This is the search regex that searchers for the "foo" identifier:

([^\w_]|^)foo([^\w\d_]|$)

And this is the replacement:

$1bar$2

Doing a replaceAll in something like

for foo: [1,2,3];foo&&foo;

works well, it outputs

for bar: [1,2,3];bar&&bar;

However, when we apply this to a string with two instances of the identifier separated by a single character, it only replaces the first:

foo&foo

outputs

bar&foo

This happens, I think, because the first match is "bar&" and so when analyzing the rest of the string no other match is found.

Is there a way to fix this by changing the regex only?


Solution

  • I think you are almost looking for \bfoo\b as your regex otherwise use lookarounds (?<=\W|^)foo(?=\W|$). In both ways replacement string is bar.

    Note: \d and _ are subsets of \w and [^\w] is equal to \W