使用点或逗号作为分隔符的带有或不带有小数的数字的 Python 正则表达式?

标签 python regex

我只是在学习正则表达式,现在我正在尝试匹配一个或多或少代表这个的数字:

[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*$

DEMO

>>> 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*$

DEMO

关于使用点或逗号作为分隔符的带有或不带有小数的数字的 Python 正则表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26137955/

相关文章:

Python 列表理解嵌套循环

JavaScript 正则表达式或运算符

python - 如何从 Django 获取 api 格式响应

python - 在pygame中可视化矩阵形成网格

python子进程设置shell var。然后运行命令 - 怎么样?

python - 为什么 ColumnTransformer 在运行时不接受转换器参数?

javascript - 正则表达式计算正则表达式中捕获组的数量

javascript - 使用 JavaScript RegExp 匹配完整单词

regex - 匹配键值对的 Shell 命令

c# - 使用C#从XML检索文本