http://www.perlmonks.org?node_id=359606
Category: Fun Stuff
Author/Contact Info
Description:

Regexp that matches regexes. The only difficulty is with /x modifier, so comments in following code intentionally made regexp-valid.

my ($code, $simple, $quanti, $regexp);

$code = qr/(?: (?:
    [^{}]                  # not a curly brackets
|   \{ (??{ $code }) \}    # balanced curly brackets
)* )/x;

$simple = qr/(?:
    \\ [pP] \{ \w+ \}                                       # \p{Prop}
|   \\.                                                     # escape
|   \[ (?: \\. | [^\]] )+ \]                                # [range]
|   \( \? \# [^)]+ \)                                       # (?#text)
|   \( \? [imsx]* -? [imsx]* (?: : (??{ $regexp }) )? \)    # (?imsx-i
+msx)
|   \( \? (?: [:=!>] | <[=!] ) (??{ $regexp }) \)           # (?=patte
+rn)
|   \( \? \?? \{ (??{ $code }) \} \)                        # (?{ code
+ })
|   \( \? \( (?: \d+ | \? [=!<] (??{ $regexp }) | \? \{ (??{ $code }) 
+\} ) \)
        (??{ $regexp }) (?: \| (??{ $regexp }) )? \)        # (?(1)y|n
+)
|   \( (??{ $regexp }) \)                                   # parenthe
+sis
|   [^\\|()\[\]*+?{}]                                       # single c
+har
)/x;

$quanti = qr/(?:
    (?: $simple (?: [+*?] \?? | \{ \d+ (?: , \d* )? \} \?? )?
)* )/x;

$regexp = qr/(?:
    $quanti (?: \| $quanti )*
)/x;

print $regexp =~ /^$regexp$/;