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

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