首页 > 解决方案 > 正则表达式仅在包含小数时才允许前导零

问题描述

我有一个看起来像这样的正则表达式:

bool(re.match('^(0|[.]{0,1}[1-9][.]{0,1}[0-9]*)$', "0.123"))

这很完美,但是当包含像​​上面的例子一样的小数时,它与前导零不匹配。我的目标是只匹配包含小数的前导零数字。不应匹配诸如“01”之类的字符串。可以匹配十进制数或整数的数字。

我将如何创建一个匹配的正则表达式?

一些场景:

0.01 Match
1 Match
1.2 Match
.01 Match
-0.1 Match
-1 Match
1.2.3 No Match
01 No Match
001.1 No Match
00.1 No Match

标签: pythonregex

解决方案


这是一种非正则表达式方法,看起来像通过了所有提到的测试用例:

numbers = """\
0.123
0
01
0.01
1
1.2
.01
-0.1
-1
1.2.3
-01.2
01
-01
001.1
00.1\
"""


def is_valid_num(s: str):
    unsigned_s = s.lstrip('-+')

    if unsigned_s.startswith('0'):
        try:
            if not unsigned_s[1] == '.':
                return False
        except IndexError:
            # It's just a zero (0)
            return True

    try:
        _ = float(s)
        return True
    except ValueError:
        return False


if __name__ == '__main__':
    for n in numbers.split('\n'):
        print(f'{n:<10} -> {is_valid_num(n)!r:>10}')

输出:

0.123      ->       True
0          ->       True
01         ->      False
0.01       ->       True
1          ->       True
1.2        ->       True
.01        ->       True
-0.1       ->       True
-1         ->       True
1.2.3      ->      False
-01.2      ->      False
01         ->      False
-01        ->      False
001.1      ->      False
00.1       ->      False

推荐阅读