简体   繁体   English

Javascript中的正则表达式以检查@符号

[英]Regular expression in Javascript to check for @ symbol

I am trying to detect whether a block of text (from a textarea) contains words that are prefixed with the @sign. 我正在尝试检测某个文本块(来自textarea)是否包含以@sign开头的单词。

For example in the following text: Hey @John, i just saw @Smith 例如,在以下文本中:嘿@John,我刚刚看到@Smith

It will detect John and Smith respectively without the @ symbol. 它将检测没有@符号的John和Smith。 I reckoned something like this would work: 我认为这样会起作用:

@\w\w+

My question is how do i make javascript filter the text, assuming it is stored in a variable comment? 我的问题是,假设文本存储在变量注释中,我如何使javascript过滤文本?

It should output only the names in the text that are prefixed with @ without the @ symbol. 它仅应在文本中输出以@开头且没有@符号的名称。

Regards. 问候。

You use the g (global) flag, a capture group, and a loop calling RegExp#exec , like this: 您使用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]);
}

Output: 输出:

Found: john
Found: mary

Live example | 实例 | source 资源


With thanks to @Alex K for the boundary recommendation! 感谢@Alex K的边界推荐!

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

I added a check to the regex so that it won't match email addresses, in case you're interested. 我在正则表达式中添加了一张支票,以防您感兴趣时它与电子邮件地址不匹配。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM