The solution isn't all that simple. You mention that you want to match '5163', followed by eight numeric digits. Fine. Your example, however, shows that you also want to allow for spaces embeded within the digits, and while you do want to preserve the spaces, you don't want those spaces to count as part of the eight digits. In other words, you want eight numeric digits following 5163, plus any embeded whitespace.

You could break it down into smaller problems and tackle it like this:

use strict; use warnings; while ( my $string = <DATA> ) { my $found = ''; my $count = 0; chomp $string; if ( $string =~ /(5163)/g ) { $found .= $1; while ( $string =~ /([\d ])/g and $count < 8 ) { $found .= $1; if( $1 =~ /\d/ ) { $count++; } } } print +($count == 8 ) ? "$string\t=>\t$found\n" : "$string\t\tFAILED:\ttoo few digits matche +d\n"; } __DATA__ abcdef 5163 1234 5678 1234516323493293 12345163234932934567890 12345163234567

This produces output as follows:

abcdef 5163 1234 5678 => 5163 1234 5678 1234516323493293 => 516323493293 12345163234932934567890 => 516323493293 12345613234567 FAILED too few digits matched

If I read your question right, that's what you're looking for. It doesn't check for naughty things like "123451632123abcdef45678". Given that string, it will silently drop the embeded abcdef. If you want to allow for any character to appear (not just spaces) embeded within the number, then substitute the ([\d ]) character class with (\d|.) and be sure to use the /s modifier on the regexp.


Dave


In reply to Re: How to write a regular expression to extract a number from an embedded string? by davido
in thread How to write a regular expression to extract a number from an embedded string? by jwking

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.