我正在尝试使用正则表达式来检测twitter提及。示例消息是,"@ this_matches hello there, @doesnt@match how is it going @matches"
我在用什么:
m_list = re.findall(r'(?<!w)(@w{1,15})(?=s)' ,a)
我唯一的问题是,当用户名是在字符串的末尾,它不会拿起它。例如:"@testing blah"有效,"blah @testing2"无效。因此,当字符串末尾没有字符时,它将不匹配。我怎么解决这个问题?
m_list = re.findall(r'(?<!w)(@w{1,15})(?=s|$)' ,a)
^^
添加$ assert position at end of a line
或
m_list = re.findall(r'(?<!w)(@w{1,15})b' ,a)
^^
b word boundary
您可以将最后的正向预测替换为反向预测。
m_list = re.findall(r'(?<!w)(@w{1,15})(?!S)' ,a)