我正在尝试检测遵循此形式的所有用户名:
/@[a-zA-Z0-9_.-]{3,30}/
例如,在以下字符串中
@eminem is singing with @rihanna
,该方法必须返回
["@eminem", "@rihanna"]
我尝试过以下方法:
function matchAllUsernames(str) {
const pattern = /@[a-zA-Z0-9_.-]{3,30}/g;
return [...str.matchAll(pattern)].flat();
}
const str = "@eminem is singing with @rihanna";
console.log(matchAllUsernames(str));
但是...如果我尝试使用这个字符串会怎样?
@eminem@ndsoiosd is singing with @rihanna
在这种情况下,该方法必须忽略 @eminem 和 @ndsoiosd,因为它们之间没有间隔...
function matchAllUsernames(str) {
const pattern = /@[a-zA-Z0-9_.-]{3,30}/g;
return [...str.matchAll(pattern)].flat();
}
const str = "@eminem@ndodshuoc is singing with @rihanna";
console.log(matchAllUsernames(str));
我怎样才能做到这一点?
最佳答案
您可以在 @ 之前为非单词边界添加 anchor ,并在模式末尾的右侧断言空白边界:
\B@[a-zA-Z0-9_.-]{3,30}(?!\S)
function matchAllUsernames(str) {
const pattern = /\B@[a-zA-Z0-9_.-]{3,30}(?!\S)/g;
return [...str.matchAll(pattern)].flat();
}
const str = "@eminem@ndodshuoc is singing with @rihanna";
console.log(matchAllUsernames(str));
还支持在下一个 @ 符号之前不允许使用字符 .
和 -
:
(?<!\S)@[a-zA-Z0-9_.-]{3,30}(?!\S)
关于javascript - 正则表达式 - 检测字符串中所有*分隔的*用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70903839/