2

I would like to build regular expression which checks if entered string is regular expression so if it contains |, [ and then ], ( and then ) for example:

A0[1-4].*Done or (L1 | L2).*Done'

I've build something simple like this: ".[\\[]..[\\]]" but it doesn't work at all even for simple examples. I tried with Java matcher and just simple String.matches()

3
  • A regex to identify regexes... reminds me of this xkcd Commented Jun 18, 2015 at 8:56
  • What exactly should the regex match? A valid regex, or anything that somehow looks like a regex, i.e. contains typical regex-chars? Commented Jun 18, 2015 at 8:57
  • I doubt it's possible. The problem is regular expressions describe regular languages. And one of the properties of regular languages is that they are context-free, and regex, of course, is not context free. So, regex is not a regular language itself, so couldn't be described by regex. At the same time, Tagir's answer should suit you well. Commented Jun 18, 2015 at 8:58

1 Answer 1

7

You can use Java own parser to check if the input is regular expression or not:

public boolean isRegExp(String pattern) {
    try {
        Pattern.compile(pattern);
        return true;
    }
    catch(PatternSyntaxException ex) {
        return false;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.