RonenIL
RonenIL

Reputation: 273

Perl - Generate All Matching String To A Regex

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.

Upvotes: 3

Views: 1918

Answers (4)

daxim
daxim

Reputation: 39158

2012 answer

Upvotes: 3

Kenosis
Kenosis

Reputation: 6204

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;
}

Upvotes: 1

TLP
TLP

Reputation: 67900

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.

Upvotes: 5

Kendall Frey
Kendall Frey

Reputation: 44326

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}

Upvotes: 4

Related Questions