StringUtils.replaceEach: Replace only separate words but not substring

1k views Asked by At

I need to use Apache's StringUtils.replaceEach() method for replacing set of strings. However, this methods also replaces substrings in the word. I know I can use replaceAll method with \b regex. But I wanted to know if there's a way to tell StringUtils to not replace substrings.

Thanks in advance,

3

There are 3 answers

0
MartyIX On

StringUtils class is envisioned to operate on strings in general. Yet, you can have a look at the source code:

https://github.com/apache/commons-lang/blob/master/src/main/java/org/apache/commons/lang3/StringUtils.java#L5749

There is also WordUtils class but it also does not contain what you need.

0
Sai prateek On

You can try StringUtils.repeat(), more info can be found to github.

0
Klugscheißer On

Don't think there's a flag for StringUtils but one possible hack would be to surround your replacement set with spaces. So instead of "foo" -> "bar", you'd have " foo " -> " bar ". This sadly isn't very helpful if your input may have new lines etc. instead of just spaces between words.