简体   繁体   中英

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.

For example in the following text: Hey @John, i just saw @Smith

It will detect John and Smith respectively without the @ symbol. 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?

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:

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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