我试图理解pos、endpos和slice在Python中使用RegexObject
。你知道吗
我的代码如下:
>>> import re
>>> pat=re.compile(r'^abcd')
# Starting search from index 2.
>>> print(pat.match('..abcd',2))
None
# Slicing gives a new string "abcd" hence a match for ^ is found.
>>> pat.match('..abcd'[2:])
<_sre.SRE_Match object; span=(0, 4), match='abcd'>
>>> pat=re.compile(r'abcd$')
# How does $ appear at end ?
>>> pat.match('abcd..',0,4)
<_sre.SRE_Match object; span=(0, 4), match='abcd'>
# Slicing gives a new string "abcd" hence a match for ^ is found.
>>> pat.match('abcd..'[:4])
<_sre.SRE_Match object; span=(0, 4), match='abcd'>
我的问题是:因为字符串abcd..
没有被分割成>>> pat.match('abcd..',0,4)
$
如何出现在endpos?
match
方法docs:参考^{} method ,它说
提供4的
endpos
相当于将字符串切成4的长度,因此endpos
被认为是字符串的新端,并且$
在那里匹配。这与pos
和^
的交互作用形成了奇怪的对比,后者显然不是这样工作的:相关问题 更多 >
编程相关推荐