使用点或逗号作为分隔符的带或不带小数的数字的 Python 正则表达式? [英] Python regex for number with or without decimals using a dot or comma as separator?

查看:23
本文介绍了使用点或逗号作为分隔符的带或不带小数的数字的 Python 正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

[零个或多个数字][可能是一个点或逗号][零个或多个数字]

没有点或逗号也可以.所以它应该匹配以下内容:

1123123.123.4123.456.456123, # 从这里开始是一样的,但用逗号而不是点分隔符123,4123,456,456

但不应与以下内容匹配:

0.,10a,10..11.1.2100,000.99 # 我知道这个和下面的在很多语言中都是有效的,但我只是想拒绝这些100.000,99

到目前为止,我已经想出了 [0-9]*[.,][0-9]*,但它似乎不太好用:

<预><代码>>>>进口重新>>>r = re.compile("[0-9]*[.,][0-9]*")>>>if r.match('0.1.'): 打印'它匹配!'...它匹配!>>>if r.match('0.abc'): 打印'它匹配!'...它匹配!

我觉得我做错了两件事:我没有正确使用 match 并且我的正则表达式不正确.有人能告诉我我做错了什么吗?欢迎所有提示!

解决方案

您需要通过在该字符类之后添加 ? 来使 [.,] 部分成为可选部分,并且也不要忘记添加锚点.^ 断言我们在开头,$ 断言我们在结尾.

^\d*[.,]?\d*$

演示

<预><代码>>>>进口重新>>>r = re.compile(r"^\d*[.,]?\d*$")>>>if r.match('0.1.'): 打印'它匹配!'...>>>if r.match('0.abc'): 打印'它匹配!'...>>>if r.match('0.'): 打印'它匹配!'...它匹配!

如果您不想允许单个逗号或点,请使用前瞻.

^(?=.*?\d)\d*[.,]?\d*$

演示

I'm just learning regex and now I'm trying to match a number which more or less represents this:

[zero or more numbers][possibly a dot or comma][zero or more numbers]

No dot or comma is also okay. So it should match the following:

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

But it should not match the following:

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

So far I've come up with [0-9]*[.,][0-9]*, but it doesn't seem to work so well:

>>> 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!

I have the feeling I'm doing two things wrong: I don't use match correctly AND my regex is not correct. Could anybody enlighten me on what I'm doing wrong? All tips are welcome!

解决方案

You need to make [.,] part as optional by adding ? after that character class and also don't forget to add anchors. ^ asserts that we are at the start and $ asserts that we are at the end.

^\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!

If you don't want to allow a single comma or dot then use a lookahead.

^(?=.*?\d)\d*[.,]?\d*$

DEMO

这篇关于使用点或逗号作为分隔符的带或不带小数的数字的 Python 正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆