gpt4 book ai didi

python - 为什么在 Python 中的子字符串 "not completely equivalent to slicing the string"中进行正则表达式搜索?

转载 作者:IT老高 更新时间:2023-10-28 20:56:03 24 4
gpt4 key购买 nike

作为 documentation声明,使用 regex.search(string, pos, endpos) 并不完全等同于对字符串进行切片,即 regex.search(string[pos:endpos])。它不会匹配 的正则表达式,好像 字符串从 pos 开始,所以 ^ 不匹配 子字符串的开头,但只匹配整个字符串的真正开头。但是,$ 匹配子字符串的结尾或整个字符串。

    >>> re.compile('^am').findall('I am falling in code', 2, 12)
[] # am is not at the beginning
>>> re.compile('^am').findall('I am falling in code'[2:12])
['am'] # am is the beginning
>>> re.compile('ing$').findall('I am falling in code', 2, 12)
['ing'] # ing is the ending
>>> re.compile('ing$').findall('I am falling in code'[2:12])
['ing'] # ing is the ending

>>> re.compile('(?<= )am').findall('I am falling in code', 2, 12)
['am'] # before am there is a space
>>> re.compile('(?<= )am').findall('I am falling in code'[2:12])
[] # before am there is no space
>>> re.compile('ing(?= )').findall('I am falling in code', 2, 12)
[] # after ing there is no space
>>> re.compile('ing(?= )').findall('I am falling in code'[2:12])
[] # after ing there is no space

>>> re.compile(r'\bm.....').findall('I am falling in code', 3, 11)
[]
>>> re.compile(r'\bm.....').findall('I am falling in code'[3:11])
['m fall']
>>> re.compile(r'.....n\b').findall('I am falling in code', 3, 11)
['fallin']
>>> re.compile(r'.....n\b').findall('I am falling in code'[3:11])
['fallin']

我的问题是...为什么 beginningending 匹配之间不一致?为什么使用posendposend当作真正的结束,而start/beginning没有被处理作为真正的开始/开始?

有没有什么方法可以使用 posendpos 模拟切片?因为 Python copies string when slicing在多次处理大字符串时,使用 posendpos 而不是切片会更有效,而不是仅仅引用旧的。

最佳答案

起始位置参数pos例如,对于进行词法分析器特别有用。使用 [pos:] 对字符串进行切片的性能差异并使用 pos参数可能看起来微不足道,但事实并非如此;例如,参见 JsLex lexer 中的此错误报告.

确实,^匹配字符串的真正开头;或者,如果 MULTILINE被指定,也在行首;这也是设计使然,因此基于正则表达式的扫描器可以轻松区分真正的行首/输入开头和一行上/输入内的其他点。

请注意,您也可以使用 regex.match(string[, pos[, endpos]]) 函数将匹配锚定到 pos 指定位置的开始字符串 ;因此而不是做

>>> re.compile('^am').findall('I am falling in code', 2, 12)
[]

您通常会将扫描仪实现为

>>> match = re.compile('am').match('I am falling in code', 2, 12)
>>> match
<_sre.SRE_Match object; span=(2, 4), match='am'>

然后设置posmatch.end() (在这种情况下返回 4)用于连续的匹配操作。

必须从 pos 开始找到匹配项。 :

>>> re.compile('am').match('I am falling in code', 1, 12)
>>>

(请注意 .match 如何像隐式 ^ 一样锚定在输入的开头,而不是在输入的末尾;实际上,这通常是错误的来源,因为人们认为匹配同时具有隐式^$ - Python 3.4 添加了执行此操作的 regex.fullmatch )


至于为什么endpos参数与pos不一致- 我不确切知道,但这对我来说也很有意义,因为在 Python 2 中没有 fullmatch并在那里锚定 $是确保整个跨度必须匹配的唯一方法。

关于python - 为什么在 Python 中的子字符串 "not completely equivalent to slicing the string"中进行正则表达式搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30999922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com