Search code examples
javastringreplaceall

A generic regex that will work for the following kind of string


I have a function that accepts a string.

ignoreWords.contains(InString.toLowerCase());

I want this Instring in a format as "abc" that is any string without any character. But my InString may come in a format as "abc", or ",abc". For now, I am handling it as below

ignoreWords.contains(text.toLowerCase().replaceAll(",","")));

But this Insting may be in a format as ".abc" or "abc." or "(abc)". I don't want to write multiple replaceAll function or to write multiple if statements to check whether the InString contains , or . etc.

The InString may be one of the following format ",abc", "abc,", ".abc", "abc.", ",abc,", ".abc.", ",abc.", ".abc,", "(abc)". There is a very less possibily that InString may come in this format also as ",(abc)" or "(abc)," or "(abc)." or ".(abc)" or ",(abc)," or ".(abc).".

What can be the efficient way to write a single replaceAll call using a regex which gives a solution in a short and simpler way?


Solution

  • replaceAll takes a regular expression as first parameter, so you could do this:

    ignoreWords.contains(text.toLowerCase().replaceAll("[.(),]", ""));
    

    This will replace all ., (, ) and , with an empty String.