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?

Recommended Answers

All 3 Replies

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.