How to determine if a string is not a regular expression?

I am trying to improve the performance of some code. It looks something like this:

public boolean isImportant(String token) {
    for (Pattern pattern : patterns) {
        return pattern.matches(token).find();
    }
}

I noticed that many of the patterns seem to be simple string literals without regex constructs. So I just want to save them in a separate list (importantList) and do an equality test instead of doing a more expensive pattern match, like this:

public boolean isImportant(String token) {
    if (importantList.contains(token)) return true;

    for (Pattern pattern : patterns) {
        return pattern.matches(token).find();
    }        
}

How do I programmatically determine if any string of a regular expression contains?

Edit: I should add that the answer does not have to be performance sensitive. (i.e. regular expressions can be used). I mainly deal with the performance of isImportant (), because it is called millions of times, and templates are initialized only once.

+5
4

. - ; :

Pattern regex = Pattern.compile("[$^()\\[\\]{}.*+?\\\\]");
Matcher regexMatcher = regex.matcher(subjectString);
regexIsLikely = regexMatcher.find();

. , , ( , )? , .

+3

, , ...

.

, , , .

, , , , .

+4

It is impossible to define it, since each regex pattern is nothing but a string. Also, there is almost no difference in performance since the regex is smart at the moment, and I'm sure that if the pattern and source length are the same, a validation is the first to be performed

+2
source

This is not true

    for (Pattern pattern : patterns) 

You must create one large regular expression, which is OR of all patterns; then for each entry you will be only once.

+1
source

All Articles