3

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.

TLP
  • 66,756
  • 10
  • 92
  • 149
RonenIL
  • 273
  • 3
  • 8
  • 17
  • 2
    I agree with Kendall Frey's comment below, you are probably trying to do something the wrong way, so you should probably try to describe your main problem situation. – TLP May 19 '12 at 14:27
  • This is a frequently asked question. I downvoted this for lack of research. - Edit: and indeed, it has come up on SO before: http://stackoverflow.com/questions/4208733/generative-regular-expressions http://stackoverflow.com/questions/4605289/listing-all-patterns-that-a-regex-matches – daxim May 19 '12 at 14:53
  • maybe you should learn something about regular languages and other stuff about formal grammatics? – gaussblurinc May 19 '12 at 14:57

4 Answers4

5

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.

TLP
  • 66,756
  • 10
  • 92
  • 149
4

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}
Kendall Frey
  • 43,130
  • 20
  • 110
  • 148
  • Thanks,what is the efficient way of generating these strings? – RonenIL May 19 '12 at 14:13
  • 1
    You will need to use something other than a regex, since regexes are too flexible. Also, *there is no efficient way*. The best you can get is exponential time. I don't know what your problem is, but I'd guess there is a good chance you are doing it wrong. – Kendall Frey May 19 '12 at 14:21
  • there is no problem, i just want to generate all these number for testing purposes. – RonenIL May 21 '12 at 06:42
3

2012 answer

Dan Dascalescu
  • 143,271
  • 52
  • 317
  • 404
daxim
  • 39,270
  • 4
  • 65
  • 132
1

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;
}
Kenosis
  • 6,196
  • 1
  • 16
  • 16