所以我應該得到一個字符串并能夠按順序將其分成許多標記。所以如果我的字符串是 25 + 90 - x * z30 我的輸出應該是 Line: 25 + 90 - x * z30數量:25標點符號:+數量:90標點符號:-標識符:x標點符號:*識別:z30目前我的代碼還處于早期階段txt = '25 + 90 - x * z30'number = '[0-9]+'identifier = '[a-zA-z][a-zA-Z0-9]*'punctuation = '[(/*+)-]' id = re.search(identifier, txt) num = re.search(number, txt) punc = re.search(punctuation, txt) print('Line: ', txt) print('Identifier: ', id) print('Number: ', num) print('punctuation', punc)我很困惑如何在第一次搜索后繼續閱讀字符串以獲得每個類別的下一次搜索以及如何讓它們按順序出現。我必須做一個特定的循環才能得到這樣的結果嗎?因為目前我只能對每個搜索進行第一次搜索,并且按照其硬編碼的順序進行搜索
1 回答

慕姐8265434
TA貢獻1813條經驗 獲得超2個贊
一種方法是將字符串拆分為標記(txt.split()可以),然后檢查每個標記以查看它匹配的正則表達式。像這樣的東西(未經測試)。
print("Line:", txt)
for token in txt.split():
id = re.search(identifier, token)
num = re.search(number, txt)
punc = re.search(punctuation, txt)
if id and id.group(0) == token: # there was a match, and the match was the whole token
print("Identifier:", token)
elif num and num.group(0) == token:
print("Number:", token)
elif punc and punc.group(0) == token:
print("Punctuation:", token)
else:
print("Unrecognized:", token)
有更好的方法可以做到這一點。例如,您可以將正則表達式放入字典中并對其進行迭代,而不是編寫 s 鏈if。
添加回答
舉報
0/150
提交
取消