[英]Regular expression to find a mention
I'm looking for a regular expression in Javascript that would match, in a string like 我正在寻找一个Javascript中的正则表达式,在一个字符串中匹配
@Mr. Smith Hello !
, where Mr. Smith is the name of the user, the occurrences ,史密斯先生是用户的名字,发生的事件
Mr.
Mr. Smith
Mr. Smith Hello
Mr. Smith Hello !
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 !
Mr. Smith Hello !
, ,
while neglecting Mr.
, Mr. Smith
and Mr. Smith Hello
... 而忽视Mr.
, Mr. Smith
与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 ): 但是,您可以创建嵌套捕获组,如下所示(演示: 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. 当然,这只适用于您提供的精确字符串格式,正好有3个空格/ 4个单独的单词。 A better solution is to make use of the substring
and split
methods, then you can recombine the parts manually: 更好的解决方案是使用substring
和split
方法,然后您可以手动重新组合部件:
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/ 演示: http : //jsfiddle.net/jbk4h/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.