Search code examples
javaregexreplaceall

How can I remove strings from text?


I have a long list of words that I want to remove from my text. For example, I have following text:

blah blah search bla code blah will blah not blah help

Now I want to remove the words, SEARCH, CODE, WILL, NOT, HELP from above string.

How can I do it easily in Java?

I am trying the following code:

someString = someString.replaceAll("\\b(search|code|will|not|help)\\b", "");

However, I noticed that sometime it doesn't replace couple of words. For example, I was using word "code" to replace but it didn't replace it (above small example works though). I have huge files that I cannot copy past here :(

Is there any other way to perform the same task? or is there any way to find out what is causing this problem? Any test case?


Solution

  • Not sure I understand the question correctly. What's wrong with doing:

    "blah blah search blah will blah not blah help".replaceAll("(search|will|not|help)", "")