获取所有以@字符开头的单词

时间:2019-10-21 13:41:09

标签: javascript regex

我正在尝试使用此正则表达式从开头为@的字符串中检索单词。

'@yoMan is going crazy with @yoker-wiy'.match(/\b@\S+\b/g)

它不起作用。它仅适用于字母,不适用于@或#

我之前尝试使用/@(\w+)/g,但是它从单词-wiy中删去了yoker。抱歉,使用正则表达式根本不好。

我认为这个问题有一个我找不到的重复项。感谢您的帮助。

3 个答案:

答案 0 :(得分:1)

  

我早些时候尝试过/ @(\ w +)/ g,但它从单词中删去了-wiy   约克

因为\ w包含alphabets ( both case ), digits and _不包含-,所以您只能得到utpo @yorker


只需使用splitfilterstartsWith

let str = '@yoMan is going crazy with @yoker-wiy';
let final = str.split(/\s+/)
               .filter(v => v.startsWith('@'))
console.log(final)


匹配后,您可以使用@[^\s]+

let str = '@yoMan is going crazy with @yoker-wiy';
let final = str.match(/@[^\s]+/g)
             
console.log(final)

答案 1 :(得分:0)

const re = '@yoMan is going crazy with @yoker-wiy'.match(/(?:^|\W)@(\w+|^-)(?!\w)/g);
   console.log(re);

这是您要查找的正则表达式。

答案 2 :(得分:0)

您需要将单词边界(\b)更改为行首(^)和行尾($),然后才能使用。

console.log(
  '@yoMan is going crazy with @yoker-wiy'
    .split(/\s+/g)
    .filter(s => s.match(/^@\S+$/g))
);
.as-console-wrapper { top: 0; max-height: 100% !important; }