How to validate numeric values which may contain dots or commas?

后端 未结 6 1194
情歌与酒
情歌与酒 2020-12-13 05:31

I need a regular expression for validation two or one numbers then , or . and again two or one numbers.

So, these

6条回答
  •  隐瞒了意图╮
    2020-12-13 06:13

    \d means a digit in most languages. You can also use [0-9] in all languages. For the "period or comma" use [\.,]. Depending on your language you may need more backslashes based on how you quote the expression. Ultimately, the regular expression engine needs to see a single backslash.

    * means "zero-or-more", so \d* and [0-9]* mean "zero or more numbers". ? means "zero-or-one". Neither of those qualifiers means exactly one. Most languages also let you use {m,n} to mean "between m and n" (ie: {1,2} means "between 1 and 2")

    Since the dot or comma and additional numbers are optional, you can put them in a group and use the ? quantifier to mean "zero-or-one" of that group.

    Putting that all together you can use:

    \d{1,2}([\.,][\d{1,2}])?
    

    Meaning, one or two digits \d{1,2}, followed by zero-or-one of a group (...)? consisting of a dot or comma followed by one or two digits [\.,]\d{1,2}

提交回复
热议问题