对子字符串应用正则表达式而不使用字符串Sli

2024-05-19 18:42:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从某个位置开始在一个较大的字符串中搜索正则表达式匹配项,并且不使用字符串切片。在

我的背景是我想迭代地在字符串中搜索各种正则表达式的匹配项

re.match(regex, largeString[pos:])

一个循环。但是对于真正大的字符串(~1MB),如largeString[pos:]中的字符串切片会变得昂贵。我在想办法避开这个问题。在

旁注:有趣的是,在Python documentation的一个小生境中,它讨论了匹配函数的可选pos参数(这正是我想要的),这是函数本身找不到的:-)。在


Tags: 函数字符串posre参数documentationmatch切片
3条回答
>>> import re
>>> m=re.compile ("(o+)")
>>> m.match("oooo").span()
(0, 4)
>>> m.match("oooo",2).span()
(2, 4)

pos关键字仅在方法版本中可用。例如

re.match("e+", "eee3", pos=1)

无效,但是

^{pr2}$

有效。在

具有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)

相关问题 更多 >