在Javascript中使用正则表达式来检查@符号

时间:2012-06-12 15:57:01

标签: javascript regex

我正在尝试检测文本块(来自textarea)是否包含以@sign为前缀的单词。

例如在下面的文字中:嘿@John,我刚刚看到@Smith

分别在没有@符号的情况下检测John和Smith。我认为这样的事情会起作用:

@\w\w+

我的问题是如何让javascript过滤文本,假设它存储在变量注释中?

它应该只输出文本中带有前缀@的名称而不带@符号。

的问候。

4 个答案:

答案 0 :(得分:5)

您使用g(全局)标志,捕获组和调用RegExp#exec的循环,如下所示:

var str = "Hi there @john, it's @mary, my email is mary@example.com.";
var re = /\B@(\w+)/g;
var m;

for (m = re.exec(str); m; m = re.exec(str)) {
    console.log("Found: " + m[1]);
}

输出:

Found: john
Found: mary

Live example | source


感谢@Alex K提出的边界建议!

答案 1 :(得分:1)

comment.match(/@\w+/g)会为您提供一系列匹配项(["@John", "@Smith"])。

答案 2 :(得分:1)

我在正则表达式中添加了一张支票,以便在您感兴趣的情况下与电子邮件地址不匹配。

var comment = "Hey @John, I just saw @Smith."
        + " (john@example.com)";

// Parse tags using ye olde regex.
var tags = comment.match(/\B@\w+/g);

// If no tags were found, turn "null" into
// an empty array.
if (!tags) {
    tags = [];
}

// Remove leading space and "@" manually.
// Can't incorporate this into regex as
// lookbehind not always supported.
for (var i = 0; i < tags.length; i++) {
    tags[i] = tags[i].substr(1);
}

答案 3 :(得分:0)

var re = /@(\w+)/g; //set the g flag to match globally
var match;
while (match = re.exec(text)) {
    //match is an array representing how the regex matched the text.
    //match.index the position where it matches.
    //it returns null if there are no matches, ending the loop.
    //match[0] is the text matched by the entire regex, 
    //match[1] is the text between the first capturing group.
    //each set of matching parenthesis is a capturing group. 
}