2024-04-18 21:38:19 发布
网友
想知道从"blah blah blah test.this@gmail.com blah blah"中匹配"test.this"的最佳方法是什么?使用Python。
"blah blah blah test.this@gmail.com blah blah"
"test.this"
我试过re.split(r"\b\w.\w@")
re.split(r"\b\w.\w@")
在正则表达式中,您需要对点"\."进行转义,或者在字符类"[.]"中使用它,因为它是正则表达式中的元字符,与任何字符都匹配。
"\."
"[.]"
此外,您需要\w+而不是\w来匹配一个或多个单词字符。
\w+
\w
现在,如果您想要test.this内容,那么split不是您所需要的。split将围绕test.this拆分字符串。例如:
test.this
split
>>> 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'
在正则表达式中,您需要对点
"\."
进行转义,或者在字符类"[.]"
中使用它,因为它是正则表达式中的元字符,与任何字符都匹配。此外,您需要
\w+
而不是\w
来匹配一个或多个单词字符。现在,如果您想要
test.this
内容,那么split
不是您所需要的。split
将围绕test.this
拆分字符串。例如:您可以使用^{} :
regex中的
.
是一个元字符,用于匹配任何字符。要匹配文字点,需要对其进行转义,因此\.
所以,如果你想计算点的文学性,我想你应该把它放在方括号里:
相关问题 更多 >
编程相关推荐