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

regex to extract value from a string

by Anonymous Monk
on Jul 01, 2020 at 06:59 UTC ( [id://11118751]=perlquestion: print w/replies, xml ) Need Help??

Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

i am trying to fetch a value from a string after _ using regex and try to store that value in a variable that i can use somewhere else, like below....also we can have any number in place of 5 like 8, 9 , 10 or 20

my $job = "50.10-d557_5"; my $Path = ""; $path = /home/data/5/file1.log

Replies are listed 'Best First'.
Re: regex to extract value from a string (updated)
by AnomalousMonk (Archbishop) on Jul 01, 2020 at 07:10 UTC

    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().


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

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (5)
As of 2024-03-28 08:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found