Tuesday, March 15, 2011

Regex to validate regex [closed]

Duplicate of http://stackoverflow.com/questions/362793/regexp-that-matches-valid-regexps

How do you produce a regex that matches only valid regex?

For instance: "[hc]at" would be valid (matching "hat" and "cat"), but "[hcat" would be invalid, as it is missing ].

From stackoverflow
  • In general, no, because nested pairs of parens and brackets, etc., is something you need a recursive descendant parser (or similar) to handle.

  • In Java you can check a regular expression by calling

    // Create a pattern to match breaks
        Pattern p = Pattern.compile("[,\\s]+");
    

    compile methode throws PatternSyntaxException if the expression's syntax is invalid

  • This question has been asked and answered before:

    http://stackoverflow.com/questions/362793/regexp-that-matches-valid-regexps

  • Use the right tool for the job. A better solution would be to use the RegEx class of the language you are using.

    Something like:

    >  Regex rx = new Regex("[INVALID REGEX
    > HERE");  if(rx.Valid())  {    ...  }
    

0 comments:

Post a Comment