tags:

views:

748

answers:

4

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 ].

+1  A: 

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

Adam Bellaire
+1  A: 

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

Markus Lausberg
+2  A: 

This question has been asked and answered before:

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

Aron Rotteveel
+2  A: 

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())  {    ...  }
moogs