我想在一个更大的字符串中搜索正则表达式匹配从某个位置开始,并且不使用字符串切片。
我的背景是我想在一个字符串中迭代搜索各种正则表达式的匹配项。 Python 中的一个自然解决方案是跟踪字符串中的当前位置并使用例如
re.match(regex, largeString[pos:])
在循环中。但是对于非常大的字符串(~ 1MB),largeString[pos:]
中的字符串切片变得很昂贵。我正在寻找一种方法来解决这个问题。
旁注:有趣的是,在 Python documentation 的一个小众市场中,它讨论了匹配函数的可选 pos
参数(这正是我想要的),函数本身找不到它:-)。
最佳答案
具有 pos 和 endpos 参数的变体仅作为正则表达式对象的成员存在。试试这个:
import re
pattern = re.compile("match here")
input = "don't match here, but do match here"
start = input.find(",")
print pattern.search(input, start).span()
... 输出 (25, 35)
关于python - 在不使用字符串切片的情况下将正则表达式应用于子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6291038/