in reply to How to write a regular expression to extract a number from an embedded string?

As others have said, your specifications are pretty incomplete. Here's another one that will preserve whitespace, but doesn't allow anything but whitespace between the numbers.
my $numbers = $string =~ /(5163(?:\s*\d){8})/;
If you want to allow anything in there (not just space, but letters or punctuation) you could use
my $numbers = $string =~ /(5163(?:\D*\d){8})/;
It's all about figuring out exactly what you want.

Replies are listed 'Best First'.
Re^2: How to write a regular expression to extract a number from an embedded string?
by davido (Cardinal) on Jul 28, 2004 at 20:28 UTC

    This example fails because you're counting whitespace as part of the eight digits. Look again at the example the OP gave. He wants eight numeric digits after 5163, with the possibility of embeded whitespace. Your example would match "51631       8". That's not what he was asking for. His example output includes "5163 1234 5678" Your solution would provide "5163 1234 56" because it is counting spaces as part of the eight digits.


    Dave

      No, it isn't. I'm allowing (optional) whitespace before the digits, but it's not counting. Look again at the part that says
      (?:\s*\d){8}
      That is, exactly 8 occurences of (any number of spaces followed by) a single digit. What my code did do wrong is that it assigned $numbers to the result of the check in scalar context, not in list context. But
      my ($numbers) = $string =~ /(5163(?:\s*\d){8})/;
      will work. If you don't believe me, test it out.
        You're right. Good job. Sorry for the errant post. ;)

        Dave