Hello, I'm just wondering how you would go about exporting the matches that regex finds. For example, if I were to have the following code, which matches all the digits in a string and (supposedly) reads them into an array, which is then displayed:

@numbers = ($string =~ /\d*/);
print @numbers;

how would I make the array hold all those matches? Right now, it just sets each array to a value of 1, which I assume stands for true. So the regex returns a true/false value. How do I get the actual numbers that were matched to be put into the array?

7 Years
Discussion Span
Last Post by KevinADC

use the "g" option:

$string = 'abc 123 def 456 ghi 789';
@numbers = $string =~ /\d+/g;
print "$_\n" for @numbers;

Note I changed the quantifier * to + because * will match zero or more digits so it will match anything that is not a digit although it will just be an empty match.

That should be covered in any regexp tutorial


Thanks. I was looking through the Perl documentation on regex, and I guess I missed that somewhere.


Cool... note I removed the capturing parentheses because when you use the "g" option they are not necessary.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.