Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

AS:i:-4 AS:i:4

Is there a regex pattern that could capture the number (both -4 and 4) from these strings? I would ordinarily use /\d+/ to remove all non-numeric characters however I do not know how to handle an extra character that may or may not be there without having to use 2 regexes e.g. /-\d+/ and /\d+/.

  • Comment on Remove all non-numeric characters except for an optional negative sign (-)
  • Download Code

Replies are listed 'Best First'.
Re: Remove all non-numeric characters except for an optional negative sign (-)
by choroba (Cardinal) on Sep 09, 2016 at 12:55 UTC
    Use ? for an optional part of a regex:
    #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; for my $s (qw( AS:i:-4 AS:i:4 )) { say $s =~ /-?\d+/g; }

    See Quantifiers for details.

    ($q=q:Sq=~/;[c](.)(.)/;chr(-||-|5+lengthSq)`"S|oS2"`map{chr |+ord }map{substrSq`S_+|`|}3E|-|`7**2-3:)=~y+S|`+$1,++print+eval$q,q,a,
Re: Remove all non-numeric characters except for an optional negative sign (-)
by pme (Monsignor) on Sep 09, 2016 at 12:57 UTC
    Hi AM,

    /-?\d+/
    can do the job. '?' is for zero or one occurrence. Update: Greeting is changed.
Re: Remove all non-numeric characters except for an optional negative sign (-)
by kennethk (Abbot) on Sep 09, 2016 at 17:00 UTC

    choroba and pme answered your question. For the future, this is documented in Matching repetitions from perlretut and Quantifiers from perlre.

    Are you sure you'll never care about cases like +5, 1.2, and 1E10?


    #11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.