在字符串列表上加速 re.match()



假设s是一长串字符串。我想提取列表中与正则表达式匹配的元素的索引。但是当列表很长时,运行时可能会很慢。有没有办法加快搜索速度?

regex = re.compile('^x.*$')
result = [i for i,v in enumerate(s) if regex.match(v)]

将列表拆分为块并使用python多处理或多线程。查找每个区块的匹配索引,并将每个区块开头的索引添加到匹配项中,以便最终索引与列表中的总体索引匹配。

如果你要做的只是检查字符串是否以"x"开头,你可以使用startswith

result = [i for i, v in enumerate(s) if v.startswith("x")]

$ python -m timeit -n 1000 -s 'import re; regex = re.compile("^x.*$");' '[i for i,v in enumerate(["xax", "y", "xaff"]) if regex.match(v)]'
1000 loops, best of 3: 1.62 usec per loop
$ python -m  timeit -n 1000 '[i for i, v in enumerate(["xax", "y", "xaff"]) if v.startswith("x")]'
1000 loops, best of 3: 1.17 usec per loop

最新更新