2017-06-12 385 views
0

我有一個值,我相信是一個數字,但我用來確認該值是一個數字的RegEx失敗。正則表達式來檢查一個字符串是否是一個數字

我不確定這是價值的錯還是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 

有人能向我解釋爲什麼無論我正則表達式失敗或如何,是不是多少?

謝謝。

+0

爲什麼你使用逗號? –

+2

如果您正在查找一串數字,請使用'\ d +' –

+0

在RegEx中?因爲有時候我會用逗號來遇到數字,所以我也需要考慮這些。像'2,345' – theprowler

回答

4

一個整數(整數)是一個或多個數字的序列。所以:

re.compile(r'\d+') 

但在這種情況下,你並不需要一個正則表達式,一個簡單的str.isdigit()就足夠了:

if weight.isdigit(): 
    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'也會匹配。您可以使用^$錨強制完整的匹配:

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說:你可以用[,.]取代,在正則表達式允許點(.)用作小數點以及。

+0

是在歐洲用於小數點的逗號還是一個錯字?也許'\ d +(?:[,。] \ d *)'會更好 – chris85

+1

@ chris85:在比利時逗號確實用作小數點。我不瞭解歐洲其他地區。 –

2

要匹配數字,可能的空格和逗號,你可以使用r'[\d ]+(,\d+)?' 它也會給加或不加逗號數完全匹配,但沒有無效逗號出現像,,1,,9什麼

例子它將匹配

  • 39,8
  • 1 259,12312

不會匹配:

  • ,,
  • 10,
  • ,0
+0

@ chris85確實。感謝我在正則表達式上總是太快。更新以捕獲更多案例並且不匹配其他 –

1

也許是更好這樣做?

>>> val = 92092 
>>> type(val) 
<class 'int'> 
>>> val = 893.22 
>>> type(val) 
<class 'float'> 

另外,如果你想留在正則表達式...嘗試:(\ d)+

+0

您可以通過執行以下操作來測試它是否爲int:if(type(val)== int):print('is int'); – OmaRPR

相關問題