Bijan
Bijan

Reputation: 8602

Perl: Return ALL instances of regex

I am using curl to store a website as a variable, $mystring. How would I return every single 8-digit number that starts with "810"?

I currently have:

#!/usr/local/bin/perl
my $curl = `curl ...`;
$curl =~ /(810\d+)/;
print "$1\n";

Except this only returns the first instance. How would I return ALL instances and store it in an array?

Upvotes: 0

Views: 54

Answers (3)

i alarmed alien
i alarmed alien

Reputation: 9520

You need to use the global modifier, /g, to capture all the matches.

To search for 8-digit numbers starting with 810, use \b to match word boundaries, and specify the number of digits to search for using braces; \d{5} matches 5 digits.

To store the matches in an array, you can do the following:

my @numbers = ($curl =~ /\b810\d{5}\b/g);

Upvotes: 0

Miller
Miller

Reputation: 35198

Use the /g Modifier.

Note, if you're not a regex expert, one potential solution is to pull out all numbers, and then filter out the ones that you don't want like so:

#!/usr/bin/env perl
use strict;
use warnings;

my $curl = do {local $/; <DATA>};

my @nums = grep {length == 8 && /^810/} $curl =~ /\d+/g;

print $_, "\n" for @nums;

__DATA__
Hello world
1                               # Too_short
134                             # Too_short
123456789                       # Too_long
81012345 810123456 81011111     # Pass    Too_long     Pass
81098765 81098765 181098765     # Pass    Test_repeat  Too_long_with_substring

Outputs:

81012345
81011111
81098765
81098765

However, the same can be accomplished in a single regex of course:

my @nums = $curl =~ /(?<!\d)(810\d{5})(?!\d)/g;

Upvotes: 1

choroba
choroba

Reputation: 241908

Use the /g modifier in a while loop:

my @numbers;
while ($curl =~ /(810\d{5})/g) {
    push @numbers, $1;
}
print "@numbers\n";

To find 8-digit numbers, search for 5 digits after the prefix. Moreover, if you don't want to match parts of larger numbers, check for word boundaries (\b) or look ahead and behind for non-numbers.

Upvotes: 0

Related Questions