为什么正则表达式拆分返回的组件比预期的多?

2024-03-28 16:05:53 发布

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

所以下面的regex(用python3编写)只是一部分,它将被添加到一个更大的regex中,以将url拆分为模式、域和路径。这部分正在提取路径。你知道吗

link = "http://google.com/whatever/who/jx.html"
components = re.split(r'(?<![:/])(/.*$)', link)

返回以下内容:

['http://google.com', '/whatever/who/jx.html', '']

为什么正则表达式在列表末尾返回一个额外的元素?你知道吗


Tags: 路径recomhttpurlhtmlgoogle模式
2条回答

^{} matches ^{} in your string.因此,您的字符串被分为匹配前的内容、匹配本身和匹配后的内容。得到这些元素(匹配项用方括号表示):

'http://google.com'['/whatever/who/jx.html']''

因此,最终生成的数组:

['http://google.com', '/whatever/who/jx.html', '']

Specified by:
https://docs.python.org/2/library/stdtypes.html#str.split

它认为最好在这里使用^{}和稍微不同的模式:

>>> import re
>>> link = "http://google.com/whatever/who/jx.html"
>>> re.match("(https?://.+?)(/.*$)", link).groups()
('http://google.com', '/whatever/who/jx.html')
>>>

下面是上面使用的正则表达式模式匹配的细分:

(        # The start of the first capture group
http     # http
s?       # An optional s
://      # ://
.+?      # One or more characters matched non-greedily
)        # The close of the first capture group
(        # The start of the second capture group
/        # /
.*       # Zero or more characters
$        # The end of the string
)        # The close of the second capture group

相关问题 更多 >