Skip to main content
 首页 » 编程设计

python之从python中的字符串中剥离@标签

2025年05月04日12cloudgamer

我正在尝试使用正则表达式从 python 中的字符串中删除@tags 但是当我尝试这样做时

str = ' you @warui  and @madawar ' 
h = re.search('@\w*',str,re.M|re.I) 
print h.group() 

它只输出第一个@tag。

@warui 

当我在 http://regexr.com?304a6 上尝试时它有效

请您参考如下方法:

“使用正则表达式从字符串中删除@tags”

import re 
 
text = ' you @warui  and @madawar ' 
stripped_text = re.sub(r'@\w+', '', text) 
# stripped_text == ' you   and  ' 

或者您想提取它们?

import re 
 
text = ' you @warui  and @madawar ' 
tags = re.findall(r'@\w+', text) 
# tags == ['@warui', '@madawar'] 

@tag 定义为 @ 后跟至少 一个字母数字字符,这就是为什么 @\w+ 优于 @\w*。另外你不需要修改区分大小写,因为 \w 匹配小写和大写字符。