Monks ~

I wanted to write a test to see if a given scalar contains a quoted regular expression. I don't care if the regex is valid or what it matches as long as perl thinks it's a real quoted regex. I discovered that it's either much easier than I thought, or I'm missing something. Or both :)

#!/usr/bin/perl use strict; use warnings; my %qrs = ( string1 => 'foo', string2 => '(xism)', regex => qr/foo/, 'regex?' => '(?-xism:foo)', ); while( my( $key, $regex ) = each %qrs ) { print "'$key' "; print $regex =~ /\(\?\-xism:/ ? 'YES: ' : 'no: '; print $regex; print ' (and matches)' if 'foo' =~/$regex/; print "\n"; }

And here's the output:

'regex?' YES: (?-xism:foo) (and matches)
'regex' YES: (?-xism:foo) (and matches)
'string1' no: foo (and matches)
'string2' no: (xism)

It looks like creating a scalar of the pattern "(?-xism:$STUFF)" is enough to make perl believe it's a quoted regex. I've tried to find a definitive in perldoc, man pages, The Camel, etc. answer and haven't.

Is it really this cool and simple?


--
man with no legs, inc.

In reply to Walks like a regex, quacks like a regex... by legLess

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.