我有一个我认为是数字的值,但我用来确认该值是数字的正则表达式失败了。
我不确定这是值的错误还是 RegEx 的错误,因为这个 RegEx 在过去的案例中对我有用。
regnumber = re.compile(r"(\d),(\d) | (\d)")
print("final weight:", weight)
if regnumber.search(weight):
print("weight = an int")
else:
print("weight does not = int")
这段代码产生:
final weight: 7088
weight does not = int
有人可以向我解释为什么我的 RegEx 失败或者为什么它不是数字吗?
谢谢。
最佳答案
整数(整数)是一个或多个数字的序列。所以:
re.compile(r'\d+')
但在那种情况下你不需要正则表达式,一个简单的 str.isdigit()
就足够了:
if <b>weight.isdigit()</b>:
print("weight = an int")
else:
print("weight does not = int")
一个十进制数,可以用下面的正则表达式匹配:
re.compile(r'\d+(?:,\d*)?')
所以你可以检查输入:
regnumber = re.compile(r'\d+(?:,\d*)?')
print("final weight:", weight)
if regnumber.match(weight):
print("weight = a number")
else:
print("weight does not = number")
请注意,正则表达式将查找任何 子序列。所以 'foo123,45bar'
也会匹配。您可以使用 ^
和 $
anchor 强制完全匹配:
regnumber = re.compile(r'^\d+(?:,\d*)?$')
print("final weight:", weight)
if regnumber.match(weight):
print("weight = a number")
else:
print("weight does not = number")
赞@chris85说:您可以将正则表达式中的 ,
替换为 [,.]
以允许将点 (.
) 用作小数点
关于python - 正则表达式检查字符串是否为数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44506983/