简体   繁体   中英

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

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM