Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex which matches any valid regular expression

Tags:

c#

regex

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

like image 470
Brian Sweeney Avatar asked Jul 26 '10 14:07

Brian Sweeney


People also ask

Is there a regular expression to detect a valid regular expression?

No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars. There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes.

What regex matches any character?

Matching a Single Character Using Regex By default, the '. ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.

How do you match expressions in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).


1 Answers

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);
like image 73
Joey Avatar answered Oct 03 '22 03:10

Joey