使用正则表达式 ^(?:100(?:\.0{1,6})?|\d{0,2}(?:\.\d{1,6})?)$
。
该正则表达式的含义为:
^
匹配字符串的开始。(?:100(?:\.0{1,6})?|
匹配数字100或者下面一组的内容:\d{0,2}(?:\.\d{1,6})?)
匹配0-2位数字,后面可能跟着一个小数点和1-6位数字,也可能没有。因此,该正则表达式可以匹配所有小于或等于100的数字,并且在匹配包含小数点的数字时,限制小数点后最多只能有6位数字,并去除第二个小数点的匹配。下面是示例代码的使用示例:
import re
pattern = '^(?:100(?:\.0{1,6})?|\d{0,2}(?:\.\d{1,6})?)$'
test_cases = ['100', '0.123456', '1.23.456', '101', '12.34567', '0.0000001']
for test_case in test_cases:
match = re.match(pattern, test_case)
if match:
print(f'{test_case} matched!')
else:
print(f'{test_case} not matched!')
输出结果为:
100 matched!
0.123456 matched!
1.23.456 not matched!
101 not matched!
12.34567 not matched!
0.0000001 not matched!