JavaScript正则表达式帮助!

JavaScript正则表达式帮助!,javascript,regex,Javascript,Regex,我正在尝试匹配此字符串中的@标记: @sam @gt @channel:sam dfgfdh sam@sam 现在,在regex testers中,这项工作是@[\S]+(在JS测试中设置)挑选所有以@开头的字符串,因此在它们中我得到: @sam @gt @channel:sam @sam 但在使用此代码的浏览器中: function detect_extractStatusUsers(status){ var e = new RegExp('@[\S]+', 'i'); m = e.ex

我正在尝试匹配此字符串中的@标记:

 @sam @gt @channel:sam dfgfdh sam@sam
现在,在regex testers中,这项工作是
@[\S]+
(在JS测试中设置)挑选所有以@开头的字符串,因此在它们中我得到:

@sam @gt @channel:sam @sam
但在使用此代码的浏览器中:

function detect_extractStatusUsers(status){
var e = new RegExp('@[\S]+', 'i');
m = e.exec(status);
var s= "";

if (m != null) {
    for (i = 0; i < m.length; i++) {
        s = s + m[i] + "\n";
    }
    alert(s);
}

return true;
}
功能检测\u提取状态用户(状态){
var e=new RegExp('@[\S]+','i');
m=e.exec(状态);
var s=“”;
如果(m!=null){
对于(i=0;i
我只能得到一个匹配的
@
(如果幸运的话,通常没有匹配)

我一定错过了什么,我的眼睛盯着它看了太久,看不清它是什么

有人能看出这个函数有什么问题吗

谢谢,

您需要:

  • 使用全局搜索
    g
    设置
  • 逃离你的\
  • 使用
    match
    而不是
    exec

    var e=new RegExp('@[\\S]+','gi')

    m=状态匹配(e)


您需要反复调用
exec
,直到它返回
null
。每次它都将返回一个
match
对象,其中包含该匹配的所有捕获

我冒昧地用我写函数的方式重写了你的函数:

function detect_extractStatusUsers(status){
    var rx = /(@[\S]+)/gi,
        match,
        tags = [];
    while (match = e.exec(status)) {
        tags.push(match[1]);
    }
    if (tags.length > 0) {
        alert(tags.join('\n'));
    }
}

嗯,它不起作用,它仍然只从@sam调用确切的函数(添加了g标志)中选择@s,比如:
detect\u extractStatusUsers(@sam”)我更新了我的答案,解决了您功能中的其他问题。哇,干杯,我知道这很简单。满分:D