Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: Variable matching on a regex

by furry_marmot (Pilgrim)
on Jun 17, 2010 at 20:39 UTC ( [id://845284]=note: print w/replies, xml ) Need Help??


in reply to Variable matching on a regex

If you're just trying to capture the numbers, then why not just do that?

$s = '1 23 456 789 01 23 456'; my ($d1, $d2, $d3, $d4, $d5, $d6, $d7) = $s =~ m/(\d+)/g; print "$d1, $d2, $d3, $d4, $d5, $d6, $d7\n"; # Prints: 1, 23, 456, 789, 01, 23, 456
or how about:
@results = $s =~ m/(\d+)/g; $i = 1; print("\$d", $i++, ": $_\n") for @results; # Prints: # $d1: 1 # $d2: 23 # $d3: 456 # $d4: 789 # $d5: 01 # $d6: 23 # $d7: 456

Some comments:

(?:) is used to group without retaining the value. So whatever you match there won't be remembered.

You grouped $_ with the my variables, which doesn't do any good.

Read up on how regexes work. A regex will ALWAYS start trying to match at the beginning of a string, searching forward until it finds a match. If you anchor the match with ^, such as m/(^\d+)/, then your are saying to only match something at the beginning of the line. This is faster, such as searching for /^Subject:/m in a bunch of emails, because it will fail after every line that doesn't start with 'S' and move on to the next line. But it won't match "Subject:" anywhere else in the text. That's good in this example, but bad for the matches you're doing.

The + and * modifiers are greedy, so if you try to match /(\d+)/, Perl will search forward to the first (or next if you're using /g) digit, and keep matching until there are no more digits.

You're trying to match \s+, but you aren't keeping it, and you don't really need to anchor on it, so there's no point in capturing it.

You can also match more complicated patterns and capture the results. Here I'm capturing groups of one or two digits that precede a group of 3 digits. I'm just using your data example, but it could be anything.

$s = '1 23 456 789 01 23 456'; push @results, $1 while $s =~ /((?:\b\d{1,2} )+\b\d{3,})/g; print "Match: $_\n" for @results; # Prints: # Match: 1 23 456 # Match: 01 23 456

Notice the use of

(?:) within a capturing group, so that it won't be separately captured as $2.

--marmot

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (3)
As of 2024-04-25 06:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found