RegEx to match comma separated numbers with optional decimal part

前端 未结 4 389
名媛妹妹
名媛妹妹 2020-11-30 13:16

I\'ve a regex that matches comma separated numbers with an optional two digit decimal part in a given multiline text.

/(?<=\\s|^)\\d{1,3}(,\\d{3})*(\\.\\d         


        
4条回答
  •  一生所求
    2020-11-30 13:38

    This:

    \d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d
    

    matches all of the following numbers:

    1
    12
    .99
    12.34 
    12,345.67
    999,999,999,999,999.99
    

    If you want to exclude numbers like 123a (street addresses for example), or 123.123 (numbers with more than 2 digits after the decimal point), try:

    (?<=\s|^)(\d{1,3}(,\d{3})*(\.\d\d)?|\.\d\d)(?=\s|$)
    

    A little demo (I guessed you're using PHP):

    $text = "666a 1 fd 12 dfsa .99 fds 12.34 dfs 12,345.67 er 666.666 er 999,999,999,999,999.99";
    $number_regex = "/(?<=\s|^)(?:\d{1,3}(?:,\d{3})*(?:\.\d\d)?|\.\d\d)(?=\s|$)/";
    if(preg_match_all($number_regex, $text, $matches)) {
      print_r($matches);
    }
    

    which will output:

    Array
    (
        [0] => Array
            (
                [0] => 1
                [1] => 12
                [2] => .99
                [3] => 12.34
                [4] => 12,345.67
                [5] => 999,999,999,999,999.99
            )
    
    )
    

    Note that it ignores the strings 666a and 666.666

提交回复
热议问题