我正在嘗試將多個元素與單個字串匹配,但幾乎沒有運氣。正則運算式應該回傳標記
陣列
中的所有元素,它們在字串中出現的次數與它們出現的順序相同,這將是一個非常基本的 C 編譯器的基本詞法分析演算法。
有沒有辦法可以將我的陣列轉換為元素基本上無序的作業模式?我沒有找到任何其他可以在我的情況下作業的模式,因為我的陣列元素可能出現在字串中的任何位置。
file = """
int main() {
return 2;
}"""
tokens = ['{', '}', '\(', '\)', ';', "int", "return", '[a-zA-Z]\w*', '[0-9] ']
def lex(file):
results = []
for i in tokens:
r = re.match(r".?" i ".",file)
if r != None:
results.append(r.group())
return r
輸出應該是這樣的:
r = ["int", "main", "(", ")", "{", "return", "2", ";", "}"]
uj5u.com熱心網友回復:
基于What is the Python way of doing a \Ganchored paring loop您可以使用的解決方案
import re
file = """
int main() {
return 2;
}"""
tokens = ['{','}',r'\(',r'\)',';',"int","return",r'[a-zA-Z]\w*','[0-9] ']
p = re.compile(fr"\s*({'|'.join(tokens)})")
def tokenize(w, pattern):
index = 0
m = pattern.match(w, index)
o = []
while m and index != m.end():
o.append(m.group(1))
index = m.end()
m = pattern.match(w, index)
return o
print(tokenize(file, p))
# => ['int', 'main', '(', ')', '{', 'return', '2', ';', '}']
請參閱Python 演示。請參閱正則運算式演示。
基本上,這在從字串開頭開始的零個或多個空格之后連續tokens匹配串列中的任何模式。
這也意味著您必須具有可能出現在輸入中的一整套標記模式,否則,這將在不匹配的文本中絆倒。
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/432359.html
上一篇:正則運算式替換未正確洗掉字符
