![](/img/trans.png)
[英]Order a list of string elements based on length first and then sort it based on alphabetical order for elements with matching length
[英]Matching a list of elements to a string in no order
我试图将多个元素匹配到一个字符串,但运气不佳。
正则表达式应该返回标记数组中的所有元素,它们在字符串中的出现次数与它们出现的顺序相同,这将是非常基本的 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
output 应该是这样的:
r = ["int", "main", "(", ")", "{", "return", "2", ";", "}"]
基于What is the Python way of doing a \G
anchored parsing 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', ';', '}']
基本上,这会在从字符串开头开始的零个或多个空格之后连续匹配tokens
列表中的任何模式。
这也意味着您必须有一套完整的可能出现在输入中的标记模式,否则,这将遇到不匹配的文本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.