Andrea
Andrea

Reputation: 20493

Regular expression which matches regular expressions

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?

Upvotes: 3

Views: 643

Answers (7)

El Ronnoco
El Ronnoco

Reputation: 11912

According Crockford this is a regex which matches regular expression (at least in JavaScript)

/\/(\\[^\x00-\x1f]|\[(\\[^\x00-\x1f]|[^\x00-\x1f\\\/])*\]|[^\x00-\x1f\\\/\[])+\/[gim]*/

Upvotes: 1

notnoop
notnoop

Reputation: 59307

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.

Upvotes: 17

Anon.
Anon.

Reputation: 60033

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

Upvotes: 0

Carl Smotricz
Carl Smotricz

Reputation: 67820

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.

Upvotes: 8

JaredPar
JaredPar

Reputation: 755457

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.

Upvotes: 0

Yaakov Shoham
Yaakov Shoham

Reputation: 10548

Yes. Example: This regex ^[a-z][+*]$ will match this regex z+ and this a* and this c+ and so on.

Upvotes: 0

SLaks
SLaks

Reputation: 888177

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.

Upvotes: 2

Related Questions