Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re: Return value from positive look behind

by choroba (Archbishop)
on Nov 11, 2020 at 17:05 UTC ( #11123593=note: print w/replies, xml ) Need Help??


in reply to Return value from positive look behind

What leads you to the belief? The digit is not captured, so it can't be returned.

Use parentheses to capture it. If you don't want to capture the minutes, don't use capturing parentheses:

/(\d{1,2})(?=\s(?:mins|minutes))/ # ^ ^ ~~ # | | \ # \ capture don't capture

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Return value from positive look behind
by bestresearch2 (Novice) on Nov 11, 2020 at 17:11 UTC

    Thank you! Posting the solution that worked (returns 5) for me.

    my $body_text="there are 5 minutes left in the program"; if ($body_text=~m/(\d{1,2})(?=\smins|\sminutes)/g) { print "here: " . $1 . "\n"; }
Re^2: Return value from positive look behind
by bestresearch2 (Novice) on Nov 11, 2020 at 17:15 UTC

    @Choroba: Another unusual thing happens if I run the code 2x in a row. The first if{} works but the second does not. Does the regex somehow need to reset?<\p>

    my $body_text="there are 5 minutes left in the program"; if ($body_text=~m/(\d{1,2})(?=\smins|\sminutes)/g) { print "1st try: " . $1 . "\n"; } if ($body_text=~m/(\d{1,2})(?=\smins|\sminutes)/g) { print "2nd try: " . $1 . "\n"; }
      That's because of the /g, it remembers where the match happend last time and tries to match again after it.

      map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      To illustrate the effect noted in choroba's reply try the following:

      use strict; use warnings; my $body_text="5 minutes left. Wait 6 minutes before nagging again."; if ($body_text=~m/(\d{1,2})(?=\smins|\sminutes)/g) { print "1st try: " . $1 . "\n"; } if ($body_text=~m/(\d{1,2})(?=\smins|\sminutes)/g) { print "2nd try: " . $1 . "\n"; }

      Prints:

      1st try: 5 2nd try: 6
      Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://11123593]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (10)
As of 2021-01-22 14:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Notices?