识别十进制数字的正则表达式是什么

时间:2019-07-14 16:00:30

标签: python regex

我曾尝试编写如下代码,以使用正则表达式在python中识别十进制数字。

在许多情况下都可以正常工作,但仍无法识别下面的输入内容

import re
string = input()
r = re.compile(r"([+\-.]?\d*\.\d+)\b")
if(r.match(string)):
    print(True)
else: 
    print(False)

234.2344->为此输入提供预期结果

+。3456468->为此输入提供预期结果

5.34.0->对于此输入,它应显示False

4 + 345.0->对于此输入,应打印False

3 个答案:

答案 0 :(得分:3)

这些表达式可能会验证整数和十进制数字:

^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$

^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$

如果例如1.是有效的。

DEMO 1

DEMO 2

测试

import re

regex = r"^[+-]?(?:\d+(?:\.\d+)?|\.\d+)$"

test_str = ("0.00000\n"
    "0.00\n"
    "-100\n"
    "+100\n"
    "-100.1\n"
    "+100.1\n"
    ".000\n"
    ".1\n"
    "3.\n"
    "4.")

print(re.findall(regex, test_str, re.MULTILINE))

输出

['0.00000', '0.00', '-100', '+100', '-100.1', '+100.1', '.000', '.1']

RegEx电路

jex.im可视化正则表达式:

enter image description here

如果要浏览/简化/修改该表达式,请在this demo的右上角进行解释。

答案 1 :(得分:1)

您可以使用

^[+-]?(?:\.\d+|\d+(?:\.\d+)?)$

enter image description here

Python demo | Regex Demo

答案 2 :(得分:0)

如果您不希望其与第一个小数部分匹配,请使用开头^和结尾锚点$

import re
decimal_re = re.compile(r'^\D?[+-]?\d*\.?\d+$')

cases = [
    '234.2344',
    '+.3456468',
    '5.34.0',
    '4+345.0',
    '1.5555',
    '.123123',
    '456.',
    '4.4.5.5'
]
for c in cases:
    print(decimal_re.match(c))

输出:

<re.Match object; span=(0, 8), match='234.2344'>
<re.Match object; span=(0, 9), match='+.3456468'>
None
None
<re.Match object; span=(0, 6), match='1.5555'>
<re.Match object; span=(0, 7), match='.123123'>
None
None