正则表达式用于文本中多个提到的用户名

时间:2018-01-08 12:32:45

标签: javascript node.js regex

这是我的用户名正则表达式:

/^(?=.{3,20}$)[A-Za-z][A-Za-z0-9]+(?:[.|_][A-Za-z0-9]+)*$/i

正确匹配单个用户名,例如tom.hardy。但我希望将多个用户名与前面的@字符匹配。如下文所示:

const text = "Hello @tom.hardy have you met with @john.deo1";

P.S:请不要推荐twitter-text npm;

2 个答案:

答案 0 :(得分:2)

只需在正则表达式的开头添加@

由于不区分大小写的标记,我还删除了在字符串内部匹配的锚点和简化的大小写。

var text = "Hello @tom.hardy have you met with @john.deo1";
var pattern = /@(?=.{3,20}(?:\s|$))[a-z][a-z0-9]+(?:[._][a-z0-9]+)?/ig;
var usernames = text.match(pattern);
console.log(usernames);

答案 1 :(得分:0)

试试这个:

const text = "Hello @tom.hardy have you met with @john.deo1";
var pattern = /@[A-Za-z0-9._-]*/g;
const username = text.match(pattern); // ["@tom.hardy", "@john.deo1"]