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

How do I match numbers with commas such as 23,898 34,676,676 and 23. This is how I match numbers with no commas-
if($tag =~ /^(\d+)$/)

Replies are listed 'Best First'.
Re: Match number with commas
by jdporter (Paladin) on Jan 30, 2003 at 21:47 UTC
    /^\d{1,3}(,\d{3})*$/

    jdporter
    The 6th Rule of Perl Club is -- There is no Rule #6.

      thank you.
      how would I store the matched number, without the commas, in a variable. $num = 23564, instead of $num = 23,678.

        The following is off the cuff, but it might work for you. Note that it also allows for negative numbers. Unlike Popcorn Dave's solution, I combine the test and the number extraction into one step. You may or may not like this. (and I just cleaned up the code)

        #!/usr/bin/perl -l use strict; use warnings; my @numbers = ( 23, '1,234', '2,2', '12,234,567', -1, '-12,234', '-23,23', '999,999', 0 ); foreach my $number (@numbers) { if (my @sections = $number =~ /^(-?\d{1,3})(?:,(\d\d\d))*$/) { print join '', grep {defined} @sections; } else { # not a valid number } }

        Cheers,
        Ovid

        New address of my CGI Course.
        Silence is Evil (feel free to copy and distribute widely - note copyright text)

        Well, once you've gotten a match with the above regex, then all you need to do is delete the commas.
        $num = '654,321'; if ( $num =~ /^\d{1,3}(,\d{3})*$/ ) { $num =~ y/,//d; # delete commas } else { # not a conforming number }

        jdporter
        The 6th Rule of Perl Club is -- There is no Rule #6.

        Using a substitution does the trick for you.

        $num =~ s/\,//g

        There is no emoticon for what I'm feeling now.

        $_ = 123456789; s/ # begin substitution operator (\d{1,3}) # match and capture one-to-three digits (?= # if they are followed by: (?:\d\d\d)+ # one-or-more groups of three digits (?!\d) # that are not followed by a digit ) # end lookahead assertion /$1,/gx; # /g = perform substitution repeatedly print; #prints: 123,456,789
        (_8(|)
Re: Match number with commas
by Abigail-II (Bishop) on Jan 30, 2003 at 22:59 UTC
    use Regexp::Common; if ($tag =~ /^$RE{num}{int}{-sep => ','}$/) { ... }

    Abigail