Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

Re: creating qr from existing regex

by bart (Canon)
on Feb 09, 2018 at 18:18 UTC ( #1208848=note: print w/replies, xml ) Need Help??


in reply to creating qr from existing regex

Remove the slashes, extract the modifier ("i") (say, in a variable $flags). Keep the core of the regex as a string, in your example that would be .*uba$.

Then put "(?$flags:" in front of it, and ")" behind it. You can use that string ($re) directly as a regex:

$re = "(?:$flags:$core)"; if($input =~ $re) { ... }
edit Oops, one too many colons:
$re = "(?$flags:$core)"; if($input =~ $re) { ... }
You can also turn it into a regex object:
$qr = qr/$re/;

Replies are listed 'Best First'.
Re^2: creating qr from existing regex
by AnomalousMonk (Chancellor) on Feb 09, 2018 at 21:07 UTC
    $re = "(?:$flags:$core)";

    That doesn't work: too many  ':' (colons):

    c:\@Work\Perl\monks>perl -wMstrict -le "my $string = '/.*uba$/i'; ;; my $flag = qr{ [msixpodual] }xms; ;; my $convertable = my ($core, $flags) = $string =~ m{ \A \s* / (.*?) / ($flag*) \z }xms; die qq{bad rx: '$string'} unless $convertable; ;; my $re = qq{(?:$flags:$core)}; print $re; print 'A: match' if 'uba' =~ $re; " (?:i:.*uba$)
    Something like this works:
    c:\@Work\Perl\monks>perl -wMstrict -le "my $string = '/.*u\/ba$/i'; ;; my $flag = qr{ [msixpodual] }xms; ;; my $convertable = my ($pattern, $modifiers) = $string =~ m{ \A \s* / (.*?) / ($flag*) \z }xms; die qq{bad rx: '$string'} unless $convertable; ;; my $rx = qr{(?$modifiers)$pattern}; print $rx; print 'A: match' if 'u/Ba' =~ $rx; ;; my $ry = qr{ \A foo $rx }xms; print $ry ;; print 'B: match' if 'foolubatU/bA' =~ $ry; print 'C: match' if 'FoolubatU/bA' =~ $ry; " (?^:(?i).*u\/ba$) A: match (?^msx: \A foo (?^:(?i).*u\/ba$) ) B: match
    Note that:
    • I go directly to  qr// form.
    • The modifiers ($flag pattern) implemented vary by Perl version; see perlop.


    Give a man a fish:  <%-{-{-{-<

      Yes, "(?:$flags:$pattern)" is wrong, it should have been "(?$flags:$pattern)". That is: the flags between the leading "(?" and ":" of the standard non-capturing grouping parens, i.e. "(?:$pattern)".

      You can always try to print out a qr/foo/i, to see what perl does natively.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1208848]
help
Chatterbox?
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (4)
As of 2018-07-20 18:52 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?















    Results (439 votes). Check out past polls.

    Notices?