简体   繁体   中英

Regular expression to find a mention

I'm looking for a regular expression in Javascript that would match, in a string like

@Mr. Smith Hello !

, where Mr. Smith is the name of the user, the occurrences

Mr. Mr. Smith Mr. Smith Hello Mr. Smith Hello !

For now, every regular expression that I tried returned

@Mr. Smith Hello ! and Mr. Smith Hello ! ,

while neglecting Mr. , Mr. Smith and Mr. Smith Hello ...

i have tried this:

/^@(.*) / , /^@(.*)* / and /^@([^ ].*) /

Thanks for your help !

A single regular expression cannot return overlapping text as separate matches, because each match consumes part of the input text. However, you can create nested capture groups, like this (Demo: http://www.rubular.com/r/bsu52a1eL9 ):

@(((([^ ]*) [^ ]*) [^ ]*) [^ ]*)

Of course this will only work for the exact string format you gave, having exactly 3 spaces / 4 separate words. A better solution is to make use of the substring and split methods, then you can recombine the parts manually:

var input = "@Mr. Smith Hello !";
var parts = input.substring(1).split(' ');
//parts = ["Mr.","Smith","Hello","!"]
var temp = "";
var output = [];

for (var i = 0; i < parts.length; i++)
{
    if (temp != "") temp += " ";
    temp += parts[i];
    output[i] = temp;
}
//output = ["Mr.", "Mr. Smith", "Mr. Smith Hello", "Mr. Smith Hello !"]

Demo: http://jsfiddle.net/jbk4h/

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