你能提供一个匹配Twitter用户名的正则表达式吗?
如果提供一个Python示例将会得到额外的奖励。
(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9-_]+)
我使用这个方法是因为它忽略了电子邮件。
这里有一个示例推文:
@你好,@你怎么样,@我的朋友,发邮件给我@ whats.up@example.com @shahmirj
匹配项:
同样的表达式也适用于hashtags,只需要将表达式中的@
替换为#
即可。
(?<=^|(?<=[^a-zA-Z0-9-_\.]))@([A-Za-z]+[A-Za-z0-9_]+)
- Angel.King.47(?<=^|(?<=[^a-zA-Z0-9-\.]))@([A-Za-z0-9_]+)
。 - rokh如果你正在谈论 Twitter 上使用的 @username
功能,那么你可以使用以下代码:
import re
twitter_username_re = re.compile(r'@([A-Za-z0-9_]+)')
要将每个实例变成HTML链接,您可以这样做:
my_html_str = twitter_username_re.sub(lambda m: '<a href="http://twitter.com/%s">%s</a>' % (m.group(1), m.group(0)), my_tweet)
我使用的正则表达式已在多个上下文中进行了测试:
/(^|[^@\w])@(\w{1,15})\b/
这是我发现的最清晰的在字符串中测试和替换Twitter用户名的方法。
#!/usr/bin/python
import re
text = "@RayFranco is answering to @jjconti, this is a real '@username83' but this is an@email.com, and this is a @probablyfaketwitterusername";
ftext = re.sub( r'(^|[^@\w])@(\w{1,15})\b', '\\1<a href="http://twitter.com/\\2">\\2</a>', text )
print ftext;
这将按预期返回我:
<a href="http://twitter.com/RayFranco">RayFranco</a> is answering to <a href="http://twitter.com/jjconti">jjconti</a>, this is a real '<a href="http://twitter.com/username83">username83</a>' but this is an@email.com, and this is a @probablyfaketwitterusername
根据Twitter规范:
你的用户名不能超过15个字符。你的真实姓名可以更长(20个字符),但为了方便起见,用户名应该保持较短。 用户名只能包含字母数字字符(A-Z字母,0-9数字),下划线是唯一例外。请检查您所需的用户名是否不包含任何符号、破折号或空格。
/@abc
中的 @-mention 和 https://medium.com/@abc
中的完整 URL - 但是没关系。) - ryanTwitter最近发布了包括Java、Ruby(gem)和Javascript实现的用于查找用户名、哈希标签、列表和URL的代码,已开源。
它非常基于正则表达式。
r'@(?i)[a-z0-9_]+'
来正确匹配所有内容,并区分用户。请注意保留 HTML 标签。(?i)
是指你的模式,而不是你捕获的值。程序仍然需要处理 ABC 和 Abc 作为相同的值。 - Kobi这是我在一个项目中使用的方法,它获取推文对象的文本属性,并将文本与标签和用户提及链接到它们在Twitter上的适当页面上,符合最新的Twitter显示指南。
def link_tweet(tweet):
"""
This method takes the text attribute from a tweet object and returns it with
user_mentions and hashtags linked
"""
tweet = re.sub(r'(\A|\s)@(\w+)', r'\1@<a href="http://www.twitter.com/\2">\2</a>', str(tweet))
return re.sub(r'(\A|\s)#(\w+)', r'\1#<a href="http://search.twitter.com/search?q=%23\2">\2</a>', str(tweet))
一旦调用此方法,您可以传递参数my_tweet[x].text。希望这对您有所帮助。
这个正则表达式看起来可以解决Twitter用户名:
^@[A-Za-z0-9_]{1,15}$
更短的,/@([\w]+)/
就可以了。
^[A-z0-9_]{5,15}$
规则:
来源:https://help.twitter.com/en/managing-your-account/twitter-username-rules
import re
pattern = re.compile('^@[A-Za-z0-9_]{1,15}$')
pattern.match('@Your_handle')
这将检查字符串是否与正则表达式完全匹配。
在“实际”环境中,您可以按照以下方式使用它:
pattern = re.compile('^@[A-Za-z0-9_]{1,15}$')
if pattern.match('@Your_handle'):
print('Match')
else:
print('No Match')