Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

regex to extract value from a string

by Anonymous Monk
on Jul 01, 2020 at 06:59 UTC ( #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 (Bishop) 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
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? | Other CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2020-08-10 16:11 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Which rocket would you take to Mars?










    Results (58 votes). Check out past polls.

    Notices?