python - 正则表达式仅在包含小数时才允许前导零
问题描述
我有一个看起来像这样的正则表达式:
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
解决方案
这是一种非正则表达式方法,看起来像通过了所有提到的测试用例:
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
推荐阅读
- android - 导航组件片段在第一次执行后卡在运行最后一行代码
- bash - Bash:脚本中的 Diff cmd 未按预期工作
- python - 递归返回列表函数停止?
- javascript - 计算 PixiJs 初始渲染所花费的时间
- python - 如何通过合并另外两个数组来制作多个数组
- visual-studio - 在 D3D12 中处理 DisplayInformation::DisplayContentsInvalidated
- windows - 使用 for 命令循环文件内容与最后一项有问题
- mysql - MySQL - 查询验证失败
- flutter - 我想在点击 api 时以 Multipart/Formdata 格式上传图像和配置文件数据,但响应失败
- node.js - 如何在我的 node/express 应用程序中添加事件侦听器?