Perl - Generate All Matching String To A Regex

1.9k Views Asked by At

I am kinda new in perl, i wanted to know if there is a way for generating all the combinations that matches a regex.

how is the best way to generate all the matching strings to :

05[0,2,4,7][\d]{7}

thanks in advance.

4

There are 4 best solutions below

3
Kendall Frey On BEST ANSWER

No there is no way to generate all matches for a certain regex. Consider this one:

a+

There is an infinite number of matches for that regex, thus you cannot list them all.

By the way, I think you want your regex to look like this:

05[0247]\d{7}
0
TLP On

While you cannot just take any regex and produce any strings it might fit, in this case you can easily adapt and overcome.

You can use glob to generate combinations:

perl -lwe "print for glob '05{0,2,4,7}'"
050
052
054
057

However, I should not have to tell you that \d{7} actually means quite a few million combinations, right? Generating a list of numbers is trivial, formatting them can be done with sprintf:

my @nums = map sprintf("%07d", $_), 0 .. 9_999_999;

That is assuming you are only looking for 0-9 numericals.

Take those nums and combine them with the globbed ones: Tada.

0
daxim On

2012 answer

0
Kenosis On

Then there is a way to generate all (four billion of) the matches for this certain regex, viz., 05[0247]\d{7}:

use Modern::Perl;

for my $x (qw{0 2 4 7}) {
    say "05$x" . sprintf '%07d', $_ for 0 .. 9999999;
}