1 回答

TA貢獻(xiàn)1813條經(jīng)驗(yàn) 獲得超2個(gè)贊
一種方法是將字符串拆分為標(biāo)記(txt.split()可以),然后檢查每個(gè)標(biāo)記以查看它匹配的正則表達(dá)式。像這樣的東西(未經(jīng)測試)。
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)
有更好的方法可以做到這一點(diǎn)。例如,您可以將正則表達(dá)式放入字典中并對(duì)其進(jìn)行迭代,而不是編寫 s 鏈if。
添加回答
舉報(bào)