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!

You
  • 167
  • 11

1 Answers1

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
Sam
  • 20,096
  • 2
  • 45
  • 71