如何在javascript中从像twitter这样的字符串中提取@提及 [英] how to pull @ mentions out of strings like twitter in javascript
问题描述
我正在用 Node.js 编写一个应用程序,它允许用户在 Twitter 等消息中相互提及.我希望能够找到用户并向他们发送通知.为了做到这一点,我需要拉 @usernames 以从 node.js 中的字符串中查找提及?
I am writing an application in Node.js that allows users to mention each other in messages like on twitter. I want to be able to find the user and send them a notification. In order to do this I need to pull @usernames to find mentions from a string in node.js?
任何建议、正则表达式、问题?
Any advice, regex, problems?
推荐答案
我发现这是在 javascript 中查找字符串中提及的最佳方法.
I have found that this is the best way to find mentions inside of a string in javascript.
var str = "@jpotts18 what is up man? Are you hanging out with @kyle_clegg";
var pattern = /B@[a-z0-9_-]+/gi;
str.match(pattern);
["@jpotts18", "@kyle_clegg"]
我特意将其限制为大写和小写字母数字和 (-,_) 符号,以避免可能与 (@j.potts) 等用户名混淆的句点.
I have purposefully restricted it to upper and lowercase alpha numeric and (-,_) symbols in order to avoid periods that could be confused for usernames like (@j.potts).
这就是 twitter-text.js 正在幕后工作.
This is what twitter-text.js is doing behind the scenes.
// Mention related regex collection
twttr.txt.regexen.validMentionPrecedingChars = /(?:^|[^a-zA-Z0-9_!#$%&*@@]|RT:?)/;
twttr.txt.regexen.atSigns = /[@@]/;
twttr.txt.regexen.validMentionOrList = regexSupplant(
'(#{validMentionPrecedingChars})' + // $1: Preceding character
'(#{atSigns})' + // $2: At mark
'([a-zA-Z0-9_]{1,20})' + // $3: Screen name
'(/[a-zA-Z][a-zA-Z0-9_-]{0,24})?' // $4: List (optional)
, 'g');
twttr.txt.regexen.endMentionMatch = regexSupplant(/^(?:#{atSigns}|[#{latinAccentChars}]|://)/);
如果您使用了更有效或更准确的方法,请告诉我.谢谢!
Please let me know if you have used anything that is more efficient, or accurate. Thanks!
这篇关于如何在javascript中从像twitter这样的字符串中提取@提及的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!