Matching numbers with regular expressions — only d

2018-12-31 08:58发布

I can't figure out how to construct a regex for the example values:

123,456,789
-12,34
1234
-8

Could you help me?

10条回答
看淡一切
2楼-- · 2018-12-31 09:06

Try this:

^-?[\d\,]+$

It will allow an optional - as the first character, and then any combination of commas and digits.

查看更多
琉璃瓶的回忆
3楼-- · 2018-12-31 09:08

For the examples:

    ^(-)?([,0-9])+$

It should work. Implement it in whichever language you want.

查看更多
旧时光的记忆
4楼-- · 2018-12-31 09:10
^-?    # start of line, optional -
(\d+   # any number of digits
|(\d{1,3}(,\d{3})*))  # or digits followed by , and three digits
((,|\.)\d+)? # optional comma or period decimal point and more digits
$  # end of line
查看更多
伤终究还是伤i
5楼-- · 2018-12-31 09:12

In java, You may use java.util.Scanner with its useLocale method

Scanner myScanner =  new Scanner(input).useLocale( myLocale)

isADouble = myScanner.hasNextDouble()
查看更多
琉璃瓶的回忆
6楼-- · 2018-12-31 09:13

Try this:

    boxValue = boxValue.replace(/[^0-9\.\,]/g, "");

This RegEx will match only digits, dots, and commas.

查看更多
长期被迫恋爱
7楼-- · 2018-12-31 09:14

Try this:

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

Allows for:

1
12
.99
12.34 
-18.34
12,345.67
999,999,999,999,999.99
查看更多
登录 后发表回答