与d匹配的正则表达式

2024-04-18 21:38:19 发布

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

想知道从"blah blah blah test.this@gmail.com blah blah"中匹配"test.this"的最佳方法是什么?使用Python。

我试过re.split(r"\b\w.\w@")


Tags: 方法testrecomthisgmailsplitblah
3条回答

在正则表达式中,您需要对点"\."进行转义,或者在字符类"[.]"中使用它,因为它是正则表达式中的元字符,与任何字符都匹配。

此外,您需要\w+而不是\w来匹配一个或多个单词字符。


现在,如果您想要test.this内容,那么split不是您所需要的。split将围绕test.this拆分字符串。例如:

>>> re.split(r"\b\w+\.\w+@", s)
['blah blah blah ', 'gmail.com blah blah']

您可以使用^{}

>>> re.findall(r'\w+[.]\w+(?=@)', s)   # look ahead
['test.this']
>>> re.findall(r'(\w+[.]\w+)@', s)     # capture group
['test.this']

regex中的.是一个元字符,用于匹配任何字符。要匹配文字点,需要对其进行转义,因此\.

"In the default mode, Dot (.) matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline." (python Doc)

所以,如果你想计算点的文学性,我想你应该把它放在方括号里:

>>> p = re.compile(r'\b(\w+[.]\w+)')
>>> resp = p.search("blah blah blah test.this@gmail.com blah blah")
>>> resp.group()
'test.this'

相关问题 更多 >