0

Is it possible to have some sort of regex that matches regex?

For example, the regex would match /(.*?)/ but not /(.?+/.

I am not really looking for an example (since I would have absolutely no idea how it works nor do I really need one) but I would like to see what you come up with as a working example.

Thanks in advance!

6
  • yes it's possible but only with regex engines that have a feature to deal with balanced parenthesis. Commented Mar 28, 2016 at 16:53
  • Do you mean to match only if the Regex is valid? Commented Mar 28, 2016 at 16:53
  • Theoretically .* will match all the regexes. Given the unicode support. But I don't understand what you are trying to accomplish here. Commented Mar 28, 2016 at 16:55
  • @NikolasCharalambidis Yes Commented Mar 28, 2016 at 16:55
  • @noob I am simply wondering if it's possible. And .* will match absolutely everything. Commented Mar 28, 2016 at 16:56

1 Answer 1

0

Short answer: Maybe.


Longer answer: It's going to be way more complicated then you want. Not to mention, there are many different flavors of regular expressions and (depending on how in depth you want to verify these expressions) you need to pick what flavor to validate. Also, some flavors of regular expressions aren't robust enough to do some of the more difficult things this expression would need to be able to do.


Suggested answer: Don't use a regular expression, but harvest the internal power of whatever programming language you are using. In other words, just try to use the expression and watch out for an exception (or any other failure).

For example, in Javascript:

function isRegexValid(expression) {
    try {
        new RegExp(expression);
        return true;
    } catch(e) {
        return false;
    }
}

console.log(isRegexValid('(.*?)')); // true
console.log(isRegexValid('(.?+'));  // false

For example, in PHP:

function isRegexValid($expression) {
    return preg_match($expression, '') !== false;
}

var_dump(isRegexValid('/(.*?)/')); // true
var_dump(isRegexValid('/(.?+/'));  // false
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.