为什么Regex不起作用?对于[^#]

2024-04-24 06:50:50 发布

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

我需要一个正则表达式匹配下面的链接模式如下。你知道吗

  1. 'https://website/1/extension1'->;True
  2. 'https://website/1.1/extension1'->;False
  3. 'https://website/1/#extension1'->;False

我的正则表达式是

regex = re.compile('https://website/1[^\.]/*[^#]')

对第二种情况有效。但是我想知道为什么在link中出现#的情况下它不返回False。你知道吗


Tags: httpsgtrefalsetrue链接模式link
1条回答
网友
1楼 · 发布于 2024-04-24 06:50:50

正则表达式与https://website/1/前缀匹配,仅此而已。除了版本号之后的/之外,字符串包含更多的文本并不重要。你知道吗

您需要包括锚点,以确保您不只是匹配子字符串。使用^$锚定到字符串的开头和结尾,这样就没有空间容纳其他字符串了。您需要匹配不包含任何#字符的路径:

^https://docs\.python\.org/\d/[^#]*$

我还对主机名中的点进行了转义,您不希望匹配'any'字符,而是希望匹配literal'.'字符。\d匹配一个数字(因此23对于主要的Python版本,不匹配更多)。你知道吗

在线演示:https://regex101.com/r/gL7X7o/3

使用Python文档URL的Python演示:

>>> import re
>>> pattern = re.compile(r'^https://docs\.python\.org/3/[^#]*$')
>>> links = [
...     'https://docs.python.org/3/library/re.html#regular-expression-syntax',
...     'https://docs.python.org/3/library/re.html',
...     'https://docs.python.org/3.6/library/re.html',
...     'https://docs.python.org/2/library/re.html',
... ]
>>> for link in links:
...     print('{!r} -> {}'.format(link, bool(pattern.search(link)))
...
'https://docs.python.org/3/library/re.html#regular-expression-syntax' -> False
'https://docs.python.org/3/library/re.html' -> True
'https://docs.python.org/3.6/library/re.html' -> False
'https://docs.python.org/2/library/re.html' -> True

相关问题 更多 >