Regex a decimal number with comma

前端 未结 3 1221
清歌不尽
清歌不尽 2021-01-05 16:50

I\'m heaving trouble finding the right regex for decimal numbers which include the comma separator.

I did find a few other questions regarding this issue in general

相关标签:
3条回答
  • 2021-01-05 17:09

    This works for all the ones that you have listed

    ^[0-9]{1,3}(,[0-9]{3})*(([\\.,]{1}[0-9]*)|())$
    
    0 讨论(0)
  • 2021-01-05 17:23

    . means "any character". To use a literal ., escape it like this: \..

    As far as I know, that's the only thing missing.

    0 讨论(0)
  • 2021-01-05 17:30

    This is a very long and convoluted regular expression that fits all your requirements. It will work if your regex engine is based on PCRE (hopefully you're using PHP, Delphi or R..).

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

    DEMO on RegExr

    The things that make it so long:

    1. Matching multiple numbers on the same line separated by only 1 character (a space) whilst not allowing partial matchs requires a lookahead and a lookbehind.
    2. Matching numbers ending with . and , without including the . or , in the match requires another lookahead.

    (?=[,.](\s|$)) Explanation

    When writing this explanation I realised the \s needs to be a (\s|$) to match 1, at the very end of a string.

    This part of the regex is for matching the 1 in 1, or the 1,000 in 1,000. so let's say our number is 1,000. (with the . on the end).

    Up to this point the regex has matched 1,000, then it can't find another , to repeat the thousands group so it moves on to our (?=[,.](\s|$))

    (?=....) means its a lookahead, that means from where we have matched up to, look at whats coming but don't add it to the match.

    So It checks if there is a , or a . and if there is, it checks that it's immediately followed by whitespace or the end of input. In this case it is, so it'd leave the match as 1,000

    Had the lookahead not matched, it would have moved on to trying to match decimal places.

    0 讨论(0)
提交回复
热议问题