Regex for Comma Separated Number or Just Number

前端 未结 5 499
情歌与酒
情歌与酒 2021-01-22 08:18

This is something of a follow up from a previous question. The requirements have changed, and I\'m looking for some help with coming up with regex for either a comma separated n

相关标签:
5条回答
  • 2021-01-22 08:35

    Why not use Int.TryParse() rathern then a regex?

    0 讨论(0)
  • 2021-01-22 08:36

    Just add an "or one or more digits" to the end:

    ^(?:\d{1,3}(?:[,]\d{3})*|\d+)$
    

    I think you had it almost right the first time and just didn't match up all your parentheses correctly.

    0 讨论(0)
  • 2021-01-22 08:40

    One thing i've noticed with all these is that the first bit of the regex allows for '0' based numbers to work. For example the number:

    0,123,456
    

    Would match using the accepted answer. I've been using:

    ((?<!\w)[+-]?[1-9][0-9]{,2}(?:,[0-9]{3})+)
    

    Which also ensures that the number has nothing in front of it. It does not catch numbers of less then 1,000 however. This was to prevent ill-formatted numbers from being captured at all. If the final + were a ? the following numbers would be captured:

    0,123
    1,2 (as 2 separate numbers)
    

    I have a strange set of numbers to match for (integers with commas, with spaces and without both), so i'm using pretty restrictive regexs to capture these groups.

    Anyway, something to think about!

    0 讨论(0)
  • 2021-01-22 08:56

    Please see this answer for a definitive treatment of the “Is it a number?” question, including allowance for correctly comma-separated digit groups.

    0 讨论(0)
  • 2021-01-22 09:02

    Try this:

    ^\d{1,3}(?:(?:,\d{3})+|\d*)$
    

    This will match any sequence that begins with one to three digits, followed by either

    • one or more segments of a comma followed by three digits, or
    • zero or more digits.
    0 讨论(0)
提交回复
热议问题