在 Twitter 中提取提及的正则表达式 [英] regex to extract mentions in Twitter

查看:60
本文介绍了在 Twitter 中提取提及的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在 python 中编写一个正则表达式来从推文中提取提及.

I need to write a regex in python to extract mentions from Tweets.

我的尝试:

regex=re.compile(r"(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9]+)")

它适用于像@mickey 这样的任何提及但是,在提及@mickey_mouse 等带有下划线的内容时,它只会提取@mickey.

It works fine for any mention like @mickey However, in mentions with underscores like @mickey_mouse, it only extracts @mickey.

如何修改正则表达式以使其在两种情况下都能正常工作?

How can I modify the regex for it to work in both cases?

谢谢

推荐答案

像这样在最后一组添加下划线:

Add an underscore to the last set like this:

(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9_]+)

Regex101 演示

附带说明,Twitter 处理规则允许您使用以数字开头的用户名 &下划线也是如此.因此,要提取 twitter 句柄,正则表达式可能很简单:@\w{1,15} (允许字符、数字和下划线,包括 15 个字符的限制).根据可能使用正则表达式的位置,需要一些额外的前瞻/后视.

On a side note, Twitter Handle rules allow you to have usernames starting with numbers & underscores as well. So to extract twitter handles a regex could be as simple as: @\w{1,15} (allows characters, numbers and underscores and includes the 15 character limit). Will need some additional lookaheads/lookbehinds based on where the regex might be used.

这篇关于在 Twitter 中提取提及的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆