我有以下情況:
Test (2.00001) Test (2.000) Test 2.1 Test (2,0001) Test 2,000 Test 2,1000 test 2
我嘗試使用正則運算式僅查找整數:
2.0002,0002
但不是其他浮點數。
我嘗試了不同的東西:
re.search('(?<![0-9.])2(?![.,]?[1-9])(?=[.,]*[0]*)(?![1-9]),...)
但這對于以下情況回傳 true:
2.000012.0002,0002,00012
我該怎么辦?
更新
我已經更新了這個問題,它也應該找到一個沒有任何逗號和點的整數(2)。
uj5u.com熱心網友回復:
我會使用:
import re
text = 'Test (2.00001) Test (2.000) Test 2.1 Test (2,0001) Test 2,000 Test 2,1000'
re.findall(r'(\d [.,]0 )(?!\d)', text)
輸出:
['2.000', '2,000']
正則運算式:
( # start capturing
\d # match digit(s)
[.,] # match . or ,
0 # match one or more zeros
) # stop capturing
(?!\d) # ensure the last zero is not followed by a digit
正則運算式演示
如果您還想單獨匹配“整數”,用空格或括號/括號括起來:
import re
text = 'Test (2.00001) Test (2.000) Test 2.1 Test (2,0001) Test 2,000 Test 2,1000 2'
re.findall(r'(?:^|[(\s[])(\d (?:[.,]0 (?!\d))?)(?=[]\s)]|$)', text)
正則運算式:
(?:^|[(\s[]) # match the start of string or [ or ( or space
( # start capturing
\d # match digit(s)
(?:[.,]0 (?!\d))? # optionally match . or , with only zeros
) # stop capturing
(?=[]\s)]|$) # match the end of string or ] or ) or space
正則運算式演示
uj5u.com熱心網友回復:
您可以使用
re.findall(r'(?<!\d)(?<!\d[.,])\d (?:[.,]0 )?(?![,.]?\d)', text)
請參閱正則運算式演示。詳情:
(?<!\d)- 左邊沒有數字(?<!\d[.,])- 沒有數字跟在.或,緊跟在左邊\d- 一位或多位數字(?:[.,]0 )?.- 一個可選的or序列,,然后是一個或多個零(?![,.]?\d)- 沒有,或.和一個數字或沒有數字允許緊挨著右邊。
如果需要支持千位分隔符:
pattern = r'(?<!\d)(?<!\d[.,])(?:\d{1,3}(?:([.,])\d{3})*|\d{4,})(?:(?!\1)[.,]0 )?(?![,.]?\d)'
matches = [x.group() for x in re.finditer(pattern, text)]
請參閱此正則運算式演示。
uj5u.com熱心網友回復:
在不需要正則運算式的情況下,您也可以is_integer()在嘗試將值轉換為各自的數字格式后考慮使用。雖然有點難以閱讀,但它消除了對正則運算式的需求,并且考慮到您提供的字串結構,對于進一步的用例應該是健壯的:
[x for x in string.split() if float((pd.to_numeric(x.replace(r'(','').replace(r')','').replace(r',','.'),errors='coerce'))).is_integer()]
回傳串列中以前的值:
['(2.000)', '2,000', '2']
或者,如果您想清潔它們:
[x for x in string.replace(r'(','').replace(r')','').replace(r',','.').split() if float((pd.to_numeric(x,errors='coerce'))).is_integer()]
回傳:
['2.000', '2.000', '2']
uj5u.com熱心網友回復:
這應該很容易 - 只需獲取一個數字并檢查“這是一個 int 值嗎?”。米比這樣的...
import re
text = 'Test (2.00001) Test (2.000) Test 2.1 Test (2,0001) Test 2,000 Test 2,1000 test 2'
out_ints = []
for x in re.findall(r'([0-9.,] )', text):
possible_int = x.replace(',', '.')
is_int = int(float(possible_int)) == float(possible_int)
if is_int:
out_ints.append(int(float(possible_int)))
print(out_ints)
輸出:
[2, 2, 2]
還是我錯過了什么?
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/531333.html
標籤:Python正则表达式
上一篇:如何在tcl中進行自動正則運算式
