开发者

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜