Alex Rivera | Logout

How to check if the string is a regular expression or not

Asked 2011-06-14T09:08:22.057
24

I have a string. How I can check if the string is a regular expression or contains regular expression or it is a normal string?

Edit
Report

3 Answers

26

The only reliable check you could do is if the String is a syntactically correct regular expression:

boolean isRegex;
try {
  Pattern.compile(input);
  isRegex = true;
} catch (PatternSyntaxException e) {
  isRegex = false;
}

Note, however, that this will result in true even for strings like Hello World and I'm not a regex, because technically they are valid regular expressions.

The only cases where this will return false are strings that are not valid regular expressions, such as [unclosed character class or (unclosed group or +.

answered 2011-06-14T09:12:11.607
2

there is no difference between a 'normal' sting and a regular expression. A regular expression is just a normal string which is used as a pattern to match occurrences of the pattern in another string.

As others have pointed out, it is possible that the string might not be a valid regular expression, but I think that is the only check you can do. If it is valid then there is no way to know if it is a regular expression or just a normal string because it will be a regular expression

It is just a normal string which is interpreted in a specific way by the regex engine.

for example "blah" is a regular expression which will only match the string "blah" where ever it occurs in another string.

When looked at this way, you can see that a regular expression does not need to contain any of the 'special characters' that do more advanced pattern matching, and it will only match the string in the pattern

answered 2011-06-14T09:11:56.707
-3
/**
 * If input string is a regex, matches will always return a false.
 */ 
public boolean isRegex(final String str) {   
    return str != null ? !str.matches(str) : false;
}
answered 2012-07-06T10:21:44.480

Your Answer