Is it possible to write a regular 开发者_开发百科expression which matches regular expressions? Does anyone have examples? If there is some theoretical obstruction, does anyone know of a regex which will match at least the most common regex patterns?
Regular expressions are not a regular language, and thus cannot be described by a regular expression!
Update: More useful practical answer
You cannot detect valid regular expressions using any regular expression. To detect its validity, you should just parse the string using the regex library and it would fail if it is an invalid regular expression. For example, in Java, it would be something like:
boolean isValidRegexp(String s) {
try {
Pattern.compile(s);
return true;
} catch (Exception e) {
return false;
}
}
This technique should work with almost any language.
You're all wrong! In my secret laboratories, my evil scientists have discovered the regular expression that can match any regular expression:
.*
It will even match the null expression. Let's see you try to match that!
As an added benefit, it will even match strings that are not regular expressions.
It is not possible using standard regular expressions.
Regular expressions can be nested indefinitely (eg, /(a(b(c(d))))/
), which is impossible to match using standard regex.
According Crockford this is a regex which matches regular expression (at least in JavaScript)
/\/(\\[^\x00-\x1f]|\[(\\[^\x00-\x1f]|[^\x00-\x1f\\\/])*\]|[^\x00-\x1f\\\/\[])+\/[gim]*/
Yes. Example: This regex ^[a-z][+*]$
will match this regex z+
and this a*
and this c+
and so on.
This is not possible. Regular expressions can only match regular languages. Regular expressions are not a regular language. If memory serves I believe they are a context-free language and require a context-free grammar to match.
Here we go:
m{/([^\\/]++|\\.)/}
Should match a regular expression delimited by //
.
Of course, it won't ensure that the regular expression parses correctly - it just identifies where it is (say, for a tokenizer).
精彩评论