Python正则表达式排除电子邮件模式,但包括@string模式
假设我拥有以下字符串:Python正则表达式排除电子邮件模式,但包括@string模式,python,regex,Python,Regex,假设我拥有以下字符串: string = "Hello, please send message to @david, @nick, @jack, but do not send message to any email address like json1234@google.com or nelson.tan@yahoo.com, thanks!" matches = re.findall("\@\w+", string) print(macthes) #return ['@david',
string = "Hello, please send message to @david, @nick, @jack, but do not send message to any email address like json1234@google.com or nelson.tan@yahoo.com, thanks!"
matches = re.findall("\@\w+", string)
print(macthes)
#return ['@david', '@nick', '@jack', '@google', '@yahoo']
但是,我只想返回['@david','@nick','@jack']
如何排除电子邮件地址的模式,使其仅返回使用@的名称标记。谢谢。由于电子邮件在
@
前面包含一个char字,您可以使用\B
:
r'\B@\w+'
此处的\B
在字符串开头匹配,或者如果@
前面有一个非单词字符(除\u
或空格以外的标点符号)。看
如果您知道需要提取的字符串在空格/字符串使用开始后
r'(?<!\S)@\w+'
使用
r'\B@\w+'
或r'(?哇,它工作得很好,我可以知道它是如何工作的吗?你应该访问下面的。
import re
s = 'Hello, please send message to @david, @nick, @jack, but do not send message to any email address like json1234@google.com or nelson.tan@yahoo.com, thanks!'
print( re.findall(r'\B@\w+', s) )
# => ['@david', '@nick', '@jack']
print( re.findall(r'(?<!\S)@\w+', s) )
# => ['@david', '@nick', '@jack']