How can I extract different number of groups of numbers from a Perl string?

I am trying to parse a string in Perl with the format:

Messages pushed to the Order Book queues 123691 121574 146343 103046 161253

I want to access the numbers at the end of the line, so I intend to do a mapping like

/(\d+)/s

My problem is that the number of values ​​at the end contains a variable number of rows.

What's the best way to format a regex to access each of these numbers individually? I'm a C ++ developer and just learning Perl, so I'm trying to find the cleanest Perl way to achieve this goal.

Thanks for your help.

+1


a source to share


4 answers


Just use the / g flag to have the match operator do global match. In the context of a list, the match operator returns all results as a list:

@result = $string =~ /(\d+)/g;

      



This works if there are no other numbers other than finite numbers.

+6


a source


You can use the match operator in the context of a list with a global flag to get a list of all your parentheses. Example:

@list = ($string =~ /(\d+)/g);

      



Your list should now contain all groups of numbers in your string. See the documentation of the matching operator for details .

+4


a source


"In a scalar context, each execution of m // g finds the next match, returns true if it matches, and false if there is no further match" - (From perldoc perlop

)

So, you should be able to create a global regex loop like:

while ($string =~ /(\d+)/g) {
    push @queuelist, $1;
}

      

+1


a source


I would do something like this:

my @numbers;
if (m/Messages pushed to the Order Book queues ([\d\s]+)/) {
   @numbers = split(/\s+/, $1);
}

      

You don't have to cram it into one regex.

0


a source







All Articles