我只是在学习正则表达式,现在我正在尝试匹配一个或多或少代表这个的数字:
[zero or more numbers][possibly a dot or comma][zero or more numbers]
没有点或逗号也可以。所以它应该匹配以下内容:
1
123
123.
123.4
123.456
.456
123, # From here it's the same but with commas instead of dot separators
123,4
123,456
,456
但它不应该匹配以下内容:
0.,1
0a,1
0..1
1.1.2
100,000.99 # I know this and the one below are valid in many languages, but I simply want to reject these
100.000,99
到目前为止,我已经想出了 [0-9]*[.,][0-9]*
,但它似乎不太好用:
>>> import re
>>> r = re.compile("[0-9]*[.,][0-9]*")
>>> if r.match('0.1.'): print 'it matches!'
...
it matches!
>>> if r.match('0.abc'): print 'it matches!'
...
it matches!
我觉得我做错了两件事:我没有正确使用 match 并且我的正则表达式不正确。有人可以启发我我做错了什么吗?欢迎所有提示!
最佳答案
您需要通过在该字符类之后添加 ?
使 [.,]
部分成为可选部分,并且不要忘记添加 anchor 。 ^
断言我们在开头,$
断言我们在结尾。
^\d*[.,]?\d*$
>>> import re
>>> r = re.compile(r"^\d*[.,]?\d*$")
>>> if r.match('0.1.'): print 'it matches!'
...
>>> if r.match('0.abc'): print 'it matches!'
...
>>> if r.match('0.'): print 'it matches!'
...
it matches!
如果您不想使用单个逗号或点,则使用先行。
^(?=.*?\d)\d*[.,]?\d*$
关于使用点或逗号作为分隔符的带有或不带有小数的数字的 Python 正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26137955/