关于关于芬德尔()python中的方法

2024-04-16 04:35:25 发布

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

我想去掉一串标点符号,结果用了

re.findall(r"[\w]+|[^\s\w]", text)

它工作得很好,确实解决了我的问题。我不明白的是括号内的细节和整个模式。r"[\w]+|[^\s\w]"到底是什么意思?我在python标准库中找到它,它说:

^{pr2}$

Return all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found. If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result unless they touch the beginning of another match.

我不确定我是否明白这一点,而且澄清听起来有点模糊。有谁能告诉我这个上下文中的模式是什么意思,它是如何在findall()方法中定义的?在


Tags: oftheinrestringmore模式one
2条回答

\w表示字母数字字符加上“u”。并且\s表示空格字符,包括“\t\r\n\v\f”和空格字符“”。所以,[\w]+|[^\s\w]意味着一个只包含单词和“uu”的字符串。在

为了分解它,[]创建一个character class。您经常会看到类似[abc]的内容,它将匹配ab或{}。相反,您也可能会看到[^abc]将匹配任何不是ab或{}的内容。最后,您还将看到字符范围:[a-cA-C]。这引入了两个范围,它将匹配abcABC中的任何一个。在

在本例中,character类包含特殊标记。\w和{}。\w匹配任何类似的字母。\w实际上取决于您的语言环境,但它通常与[a-zA-Z0-9_]匹配a-zA-Z0-9或{}范围内的任何内容。\s类似,但它匹配任何可以被视为空白的内容。在

+表示您可以重复前面的匹配1次或更多次。因此[a]+将匹配整个字符串aaaaaaaaaaa。在您的例子中,您匹配的是相邻的字母数字字符。在

|基本上类似于“或”。匹配左侧的内容,如果左侧的内容不匹配,则匹配右侧的内容。在

相关问题 更多 >