954,541 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Export Regex Matches

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?

orwell84
Junior Poster
102 posts since Nov 2008
Reputation Points: 17
Solved Threads: 5
 

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

KevinADC
Posting Shark
921 posts since Mar 2006
Reputation Points: 246
Solved Threads: 67
 

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

orwell84
Junior Poster
102 posts since Nov 2008
Reputation Points: 17
Solved Threads: 5
 

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

KevinADC
Posting Shark
921 posts since Mar 2006
Reputation Points: 246
Solved Threads: 67
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You