Regex that Evaluates Regexes

This question already has an answer here:

  • Is there a regular expression to detect a valid regular expression? 8 answers

  • 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
    
    链接地址: http://www.djcxy.com/p/76738.html

    上一篇: 我如何验证正则表达式?

    下一篇: 评估正则表达式的正则表达式