Regex that matches any valid regex

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

FYI, the reason I'm trying to do this is because I have a mini language that allows regular expressions as part of the syntax, and I combined crummy regex to check the statements in the mini language, but it is incorrectly mistaken in some more complex expressions. Mini-language syntax is defined using a combination of eBNF and regular expressions. I could do this "validation" in C #, but I think that if this approach is possible, it will be a clean and better separation of problems.

Thanks Brian

+5
source share
1 answer

No, you can’t. At least not in general. Regular expressions describe ordinary languages, and they are characterized by the fact that they cannot contain arbitrary nested expressions. So something like

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

it’s almost impossible to check with regular expressions only. While some regex flavors allow for recursive convergence in a match (e.g. Perl) or balanced capture groups that can mimic this to some extent, this is definitely not a tool designed for this job, and you should not try to train it alone.

What you can do is simply try to compile the expression you want to test. The .NET regular expression engine throws an exception if the template is invalid:

var compiledRegex = new Regex(someString);
+10
source

All Articles