Skip to main content
 首页 » 编程设计

python之正则表达式检查字符串是否为数字

2025年05月04日19haluo1

我有一个我认为是数字的值,但我用来确认该值是数字的正则表达式失败了。

我不确定这是值的错误还是 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说:您可以将正则表达式中的 , 替换为 [,.] 以允许将点 (.) 用作小数点