为什么在Python中使用正则表达式搜索"不完全等同于切割字符串"?

fik*_*r4n 19 python regex string substring

正如文档所述,使用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']
Run Code Online (Sandbox Code Playgroud)

我的问题是......为什么在开始结束比赛之间不一致?为什么使用posendpos处理结束作为真正的结束,但开始/开始不被视为真正的开始/开始?

是否有任何方法可以使用posendpos模仿切片?因为Python 在切片时复制字符串而不是仅仅引用旧字符串,所以在使用大字符串多次时使用posendpos不是切片会更有效.

Sam*_*ley 0

这听起来像是 Python 中的一个错误,但如果您想通过引用进行切片而不是复制字符串,您可以使用 Python 内置buffer.

例如:

s = "long string" * 100
buf = buffer(s)
substr = buf([5:15])
Run Code Online (Sandbox Code Playgroud)

这会在不复制数据的情况下创建子字符串,因此应该允许有效地分割大字符串。