我正在寻找一种方法,让一个或多个用户名在@字符串中以符号开头.
一些示例字符串可能是:
有解决方案吗 我找不到任何东西.
提前致谢!
要匹配单个事件,请使用不带任何修饰符的正则表达式,然后删除@使用.replace("@", ""):
var myString = "Hey @username this is a test string";
var username = myString.match(/@[a-z0-9_]*/)[0].replace("@", "");
// This will be "username"
Run Code Online (Sandbox Code Playgroud)
对于多次出现,请使用带有g修饰符的正则表达式来匹配多个字符串,然后使用该.map()方法删除@每个用户名开头的字符,并使用.replace("@", "")和.filter()删除空用户名:
var myString = "Hey @username1 and @username_two, this is just a test string! @username3";
var usernames = myString.match(/@[a-z0-9_]*/g).map(function(x) { return x.replace("@", ""); }).filter(function(x) { return !!x; });
// This will be ["username1", "username_two", "username3"]
Run Code Online (Sandbox Code Playgroud)
注意:我使用正则表达式,/@[a-z0-9_]*/g因为用户名只能包含字母,数字和下划线(至少在最常见的网站上,如Twitter等).