$如何出现在结尾?

2024-10-01 19:21:51 发布

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

我试图理解posendposslice在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?


Tags: renewstringobjectmatchspansrecompile
1条回答
网友
1楼 · 发布于 2024-10-01 19:21:51

match方法docs

The optional pos and endpos parameters have the same meaning as for the search() method.

参考^{} method,它说

The optional parameter endpos limits how far the string will be searched; it will be as if the string is endpos characters long, so only the characters from pos to endpos - 1 will be searched for a match. If endpos is less than pos, no match will be found; otherwise, if rx is a compiled regular expression object, rx.search(string, 0, 50) is equivalent to rx.search(string[:50], 0).

提供4的endpos相当于将字符串切成4的长度,因此endpos被认为是字符串的新端,并且$在那里匹配。这与pos^的交互作用形成了奇怪的对比,后者显然不是这样工作的:

the '^' pattern character matches at the real beginning of the string and at positions just after a newline, but not necessarily at the index where the search is to start.

相关问题 更多 >

    热门问题