Brian Sweeney
Brian Sweeney

Reputation: 6815

Regex which matches any valid regular expression

Does anyone know where I can come by a regex that matches any valid C# style regular expression? Is it even possible?

FYI, the reason I'm trying to do this is because I have a mini language which allows regular expressions as part of it's syntax and I cobbled together crummy regex to validate the mini-language statements but it fails incorrectly on some more complicated expressions. The mini-language syntax is defined through a combination of eBNF and regular expressions. I could do this 'validation' in C# but i think if this approach is possible, it would be cleanest and best separation of concerns.

Thanks, brian

Upvotes: 5

Views: 322

Answers (1)

Joey
Joey

Reputation: 354734

No, you can't. At least not generally. Regular expressions describe regular languages and those are characterized by the fact that they cannot contain arbitrarily nested expressions. So something like

(ab(?:cd)e(fg))

is already pretty much impossible to validate with regular expressions alone. While certain flavors of regular expressions allow recursive descent into the match (Perl, for example) or balanced capture groups which can emulate this to some extent it is definitely not the tool meant for this job and you shouldn't try to shoehorn it into one.

What you can do is just try to compile an expression you want to validate. .NET's regular expression engine will throw an exception if the pattern is invalid:

var compiledRegex = new Regex(someString);

Upvotes: 10

Related Questions