Beefy Boxes and Bandwidth Generously Provided by pair Networks
Pathologically Eclectic Rubbish Lister

Stripping out specific numbers

by mrras25 (Acolyte)
on Dec 12, 2013 at 00:03 UTC ( #1066749=perlquestion: print w/replies, xml ) Need Help??
mrras25 has asked for the wisdom of the Perl Monks concerning the following question:

Good Afternoon/Evening,

I need to know what is the best way to strip out numbers that are 4 to 5 digits in length in a string.


string: npnoa72932n02

Need : 72932 (numeric string of 5)

String: geed7812r412p

Need : 7812 (numeric string of 4)

Thank you for your help

Replies are listed 'Best First'.
Re: Stripping out specific numbers
by davido (Archbishop) on Dec 12, 2013 at 00:09 UTC

    What have you tried?


    This will capture.

    if( $string =~ m/(?<!\d)(\d{4,5})(?!\d)/ ) { print "$1\n"; }

    If you want to capture all occurrences:

    my( @found ) = $string =~ m/(?<!\d)(\d{4,5})(?!\d)/g;

    And if "strip" means remove:

    $string =~ s/(?<!\d)\d{4,5}(?!\d)//g;


Re: Stripping out specific numbers
by AnomalousMonk (Chancellor) on Dec 12, 2013 at 00:12 UTC

    One way:

    >perl -wMstrict -le "my $s = 'xx123xx4321xx56789xx987654xx'; ;; my @n = $s =~ m{ (?<! \d) \d{4,5} (?! \d) }xmsg; printf qq{'$_' } for @n; " '4321' '56789'
Re: Stripping out specific numbers
by mrras25 (Acolyte) on Dec 12, 2013 at 14:48 UTC
    Thank you all for the help - I used a combination of the 2 replies to get the disired result. To answer what I done prior to that, it was very basic. First I matched 4 or 5 number strings and then I striped out any characters leaving undisered results.
    if($string =~ m/(\d\d\d\d+)/ || $string =~ m/(\d\d\d\d\d+)/){ $string =~ s/\D//g; }
    As you can see not so good and not so desired... again thank you for your help.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1066749]
Approved by Old_Gray_Bear
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2018-06-23 18:05 GMT
Find Nodes?
    Voting Booth?
    Should cpanminus be part of the standard Perl release?

    Results (125 votes). Check out past polls.