我正在学习正则表达式,现在我正在尝试匹配一个或多或少代表这个的数字:
[zero or more numbers][possibly a dot or comma][zero or more numbers]
Run Code Online (Sandbox Code Playgroud)
没有点或逗号也没关系.所以它应该匹配以下内容:
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
Run Code Online (Sandbox Code Playgroud)
但它不应与以下内容相匹配:
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
Run Code Online (Sandbox Code Playgroud)
到目前为止,我已经提出了[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!
Run Code Online (Sandbox Code Playgroud)
我觉得我做错了两件事:我没有正确使用匹配而且我的正则表达式不正确.有人能告诉我我做错了什么吗?欢迎所有提示!
Avi*_*Raj 10
您需要[.,]通过?在该角色类之后添加并且不要忘记添加锚点来使其成为可选部分.^声称我们刚开始并$声称我们已经结束了.
^\d*[.,]?\d*$
Run Code Online (Sandbox Code Playgroud)
>>> 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!
Run Code Online (Sandbox Code Playgroud)
如果您不想允许单个逗号或点,请使用前瞻.
^(?=.*?\d)\d*[.,]?\d*$
Run Code Online (Sandbox Code Playgroud)