我试图使用正则表达式从python中的字符串中删除@tags但是当我尝试这样做时
str = ' you @warui and @madawar '
h = re.search('@\w*',str,re.M|re.I)
print h.group()
Run Code Online (Sandbox Code Playgroud)
它仅输出第一个@tag.
@warui
Run Code Online (Sandbox Code Playgroud)
当我在http://regexr.com?304a6上尝试它时,它的工作原理
"使用正则表达式从字符串中删除@tags"
import re
text = ' you @warui and @madawar '
stripped_text = re.sub(r'@\w+', '', text)
# stripped_text == ' you and '
Run Code Online (Sandbox Code Playgroud)
或者你想提取它们?
import re
text = ' you @warui and @madawar '
tags = re.findall(r'@\w+', text)
# tags == ['@warui', '@madawar']
Run Code Online (Sandbox Code Playgroud)
@tag定义为@后跟至少一个字母数字字符,这就是为什么@\w+优于@\w*.此外,您不需要修改区分大小写,因为\w匹配低位和高位字符.