Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

Re: regex to extract value from a string (updated)

by AnomalousMonk (Bishop)
on Jul 01, 2020 at 07:10 UTC ( #11118752=note: print w/replies, xml ) Need Help??


in reply to regex to extract value from a string

c:\@Work\Perl\monks>perl -wMstrict -le "for my $string (qw( 50.10-d557_5 50.10-d557_8 50.10-d557_20 50.10-d557_123 )) { my ($value) = $string =~ m{ _ (\d+) \z }xms; print qq{'$string' -> '$value'}; } " '50.10-d557_5' -> '5' '50.10-d557_8' -> '8' '50.10-d557_20' -> '20' '50.10-d557_123' -> '123'
Please see perlre, perlretut, and perlrequick. (Update: Also see articles in the Tutorials -> Pattern Matching, Regular Expressions, and Parsing section.)

Update: For completeness, here's code showing capture and use of matching/parsing success status, and also some edge-case and failing parse examples. Data::Dumper::Dumper(), which is core, can be used instead of non-core Data::Dump::dd().

c:\@Work\Perl\monks>perl -wMstrict -e "use Data::Dump qw(dd); ;; for my $string (qw( 50.10-d557_5 50.10-d557_8 50.10-d557_20 50.10-d557_123 _5 ___6 9_99_999_321 999_x 999_7x 999_ 999 _ )) { my $got_value = my ($value) = $string =~ m{ _ (\d+) \z }xms; dd $string, $value, $got_value; if ($got_value) { print qq{'$string' -> '$value' \n\n}; } else { print qq{'$string' parse failed \n\n}; } } " ("50.10-d557_5", 5, 1) '50.10-d557_5' -> '5' ("50.10-d557_8", 8, 1) '50.10-d557_8' -> '8' ("50.10-d557_20", 20, 1) '50.10-d557_20' -> '20' ("50.10-d557_123", 123, 1) '50.10-d557_123' -> '123' ("_5", 5, 1) '_5' -> '5' ("___6", 6, 1) '___6' -> '6' ("9_99_999_321", 321, 1) '9_99_999_321' -> '321' ("999_x", undef, 0) '999_x' parse failed ("999_7x", undef, 0) '999_7x' parse failed ("999_", undef, 0) '999_' parse failed (999, undef, 0) '999' parse failed ("_", undef, 0) '_' parse failed


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

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2020-09-24 12:40 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    If at first I donít succeed, I Ö










    Results (133 votes). Check out past polls.

    Notices?