if (my $list = $line =~ /\(\d+(,\d+)*\)/) { ... }
The problem with this is it only captures the match success status in the $list scalar:
Because of the way something like (,\d+)* works, changing $list to an array @list isn't much better:c:\@Work\Perl>perl -wMstrict -le "my $line = '[AHB_REPORTER][INFO]: action(62,1,0,0,0,0,5,53,9,0,190)D:/XYZ/reg/ +Tests/Mcu/A_test.cCALL: (null)'; if (my $list = $line =~ /\(\d+(,\d+)*\)/) { print qq{'$list'}; } " '1'
(This works the same with or without a /g modifier on the m// match.)c:\@Work\Perl>perl -wMstrict -le "my $line = '[AHB_REPORTER][INFO]: action(62,1,0,0,0,0,5,53,9,0,190)D:/XYZ/reg/ +Tests/Mcu/A_test.cCALL: (null)'; if (my @list = $line =~ /\(\d+(,\d+)*\)/) { print qq{(@list)}; } " (,190)
To extract all digit groups, you could do something like:
(Add \s* whitespace flavoring to taste.) (Update: The \G , pattern assumes that a , (comma) never occurs at the beginning of $line.)c:\@Work\Perl>perl -wMstrict -MData::Dump; -le "my $line = '[AHB_REPORTER][INFO]: action(62,1,0,0,0,0,5,53,9,0,190)D:/XYZ/reg/ +Tests/Mcu/A_test.cCALL: (null)'; if (my @list = $line =~ m{ (?: \G , | action\( ) (\d+) }xmsg) { printf qq{'$_' } for @list; print ''; my %hash = do { my $k = 'a'; map { $_ ? ($k++ => $_) : () } @list +}; dd \%hash; } " '62' '1' '0' '0' '0' '0' '5' '53' '9' '0' '190' { a => 62, b => 1, c => 5, d => 53, e => 9, f => 190 }
Update: If you want to get a bit fancy, do it all in one swell foop and then just test if the hash has anything in it:
(The \K regex operator comes with Perl versions 5.10+. If your version pre-dates 5.10, let me know and I'll supply a simple fix.)c:\@Work\Perl>perl -wMstrict -MData::Dump -le "my $line = '[AHB_REPORTER][INFO]: action(62,1,0,0,0,0,5,53,9,0,190)D:/XYZ/reg/ +Tests/Mcu/A_test.cCALL: (null)'; ;; my %hash = do { my $k = 'a'; map { $_ ? ($k++ => $_) : () } $line =~ m{ (?: \G , | action [(] ) \K \d+ }xmsg; }; ;; if (%hash) { dd \%hash; } else { print 'no got'; } " { a => 62, b => 1, c => 5, d => 53, e => 9, f => 190 }
In reply to Re^2: Extract a small part of a long sentence using regular expressions
by AnomalousMonk
in thread Extract a small part of a long sentence using regular expressions
by swatzz
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |