gpt4 book ai didi

python - 对正则表达式感到困惑

转载 作者:太空狗 更新时间:2023-10-30 02:47:01 25 4
gpt4 key购买 nike

Programming Collective Intelligence这本书中有一个正则表达式,

splitter = re.compile('\\W*')

从上下文来看,这似乎匹配任何非字母数字字符。但我很困惑,因为它似乎匹配一个反斜杠,然后是一个或多个 W。它真正匹配的是什么?

最佳答案

您的正则表达式等同于 \W*。它匹配 0 个或多个非字母数字字符。

实际上,您使用的是 python 字符串文字,而不是原始字符串。在 python 字符串文字中,要匹配文字反斜杠,您需要转义反斜杠 - \\,因为反斜杠在那里具有特殊含义。然后对于正则表达式,您需要转义两个反斜杠,使其成为 - \\\\

因此,要匹配 \ 后跟 0 个或多个 W,您需要在字符串文字中使用 \\\\W*。您可以使用原始字符串来简化它。其中 \\ 将匹配文字 \。这是因为,在 原始字符串 中使用时,不会以任何特殊方式处理反斜杠。

以下示例将帮助您理解这一点:

>>> s = "\WWWW$$$$"

# Without raw string
>>> splitter = re.compile('\\W*') # Match non-alphanumeric characters
>>> re.findall(splitter, s)
['\\', '', '', '', '', '$$$$', '']

>>> splitter = re.compile('\\\\W*') # Match `\` followed by 0 or more `W`
>>> re.findall(splitter, s)
['\\WWWW']

# With raw string
>>> splitter = re.compile(r'\W*') # Same as first one. You need a single `\`
>>> re.findall(splitter, s)
['\\', '', '', '', '', '$$$$', '']

>>> splitter = re.compile(r'\\W*') # Same as 2nd. Two `\\` needed.
>>> re.findall(splitter, s)
['\\WWWW']

关于python - 对正则表达式感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17704448/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com