2

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

例如在以下文本中:嘿@John,我刚看到@Smith

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

@\w\w+

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

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

问候。

4

4 回答 4

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]);
}

输出:

发现:约翰
发现:玛丽

实例| 资源


感谢@Alex K 的边界推荐!

于 2012-06-12T16:00:55.230 回答
1

comment.match(/@\w+/g)会给你一个匹配数组(["@John", "@Smith"])。

于 2012-06-12T15:59:26.900 回答
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);
}
于 2012-06-12T16:27:40.707 回答
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. 
}  
于 2012-06-12T16:00:31.527 回答