2

I have a simple method that searches for and compiles the pattern for the given string

    String search = I GIVE IT SOME STRING;
    String trimmedSearch = search.trim();
    if (trimmedSearch.isEmpty())
    {
        pattern_ = null;
    }
    else if (trimmedSearch.contains("*") || trimmedSearch.contains("(") 
        || trimmedSearch.contains(")") || trimmedSearch.contains("?")
        || trimmedSearch.contains(".") || trimmedSearch.contains("[")
        || trimmedSearch.contains("]") || trimmedSearch.contains("{")
        || trimmedSearch.contains("}") || trimmedSearch.contains("^")
        || trimmedSearch.contains("|") || trimmedSearch.contains("$")
        || trimmedSearch.contains("+") || trimmedSearch.contains("\\"))
    {
        pattern_ = null;
    }
    else
    {
        pattern_ = Pattern.compile(trimmedSearch.toUpperCase(), Pattern.CASE_INSENSITIVE);
    }

Pattern crashes miserably whenever search is *

Because of that I have the horrible huge if statement checking to make sure that the string does not contain any of the characters that can crash it. But what if I would like to also include them in the search. Is there any way?

Any help will be appreciated, it is very difficult to search for this kind of question or problem anywhere online, and I am starting to lose my mind.

Quillion
  • 6,346
  • 11
  • 60
  • 97

2 Answers2

6

Use Pattern.quote(). It quotes all regex metacharacters from its input.

If the result of this method is different from the original, you know you have at least one regex metacharacter in your input:

pattern_ = trimmedSearch.equals(Pattern.quote(trimmedSearch))
    ? Pattern.compile(trimmedSearch.toUpperCase(), Pattern.CASE_INSENSITIVE)
    : null;
fge
  • 119,121
  • 33
  • 254
  • 329
1

You can escape special characters in Strings like this

trimmedSearch = Pattern.quote(trimmedSearch);

See How to escape text for regular expression in Java

Community
  • 1
  • 1
rli
  • 1,745
  • 1
  • 14
  • 25