Javascript Regexp 循环所有匹配项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5835418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Regexp loop all matches
提问by Tom Gullen
I'm trying to do something similar with stack overflow's rich text editor. Given this text:
我正在尝试使用堆栈溢出的富文本编辑器做类似的事情。鉴于此文本:
[Text Example][1]
[1][http://www.example.com]
I want to loop each [string][int]
that is found which I do this way:
我想循环每一个[string][int]
我这样做的发现:
var Text = "[Text Example][1]\n[1][http: //www.example.com]";
// Find resource links
var arrMatch = null;
var rePattern = new RegExp(
"\[(.+?)\]\[([0-9]+)\]",
"gi"
);
while (arrMatch = rePattern.exec(Text)) {
console.log("ok");
}
This works great, it alerts 'ok' for each [string][int]
. What I need to do though, is for each match found, replace the initial match with components of the second match.
这很好用,它为每个[string][int]
. 不过,我需要做的是,对于找到的每个匹配项,用第二个匹配项的组件替换初始匹配项。
So in the loop $2 would represent the int part originally matched, and I would run this regexp (pseduo)
所以在循环中 $2 将代表最初匹配的 int 部分,我将运行这个正则表达式(伪)
while (arrMatch = rePattern.exec(Text)) {
var FindIndex = ; // This would be 1 in our example
new RegExp("\[" + FindIndex + "\]\[(.+?)\]", "g")
// Replace original match now with hyperlink
}
This would match
这将匹配
[1][http://www.example.com]
End result for first example would be:
第一个示例的最终结果是:
<a href="http://www.example.com" rel="nofollow">Text Example</a>
Edit
编辑
I've gotten as far as this now:
我现在已经做到了:
var Text = "[Text Example][1]\n[1][http: //www.example.com]";
// Find resource links
reg = new RegExp(
"\[(.+?)\]\[([0-9]+)\]",
"gi");
var result;
while ((result = reg.exec(Text)) !== null) {
var LinkText = result[1];
var Match = result[0];
Text = Text.replace(new RegExp(Match, "g"), '<a href="#">" + LinkText + "</a>');
}
console.log(Text);
采纳答案by Tom Gullen
I managed to do it in the end with this:
最后我设法做到了这一点:
var Text = "[Text Example][1]\n[1][http: //www.example.com]";
// Find resource links
reg = new RegExp(
"\[(.+?)\]\[([0-9]+)\]",
"gi");
var result;
while (result = reg.exec(Text)) {
var LinkText = result[1];
var Match = result[0];
var LinkID = result[2];
var FoundURL = new RegExp("\[" + LinkID + "\]\[(.+?)\]", "g").exec(Text);
Text = Text.replace(Match, '<a href="' + FoundURL[1] + '" rel="nofollow">' + LinkText + '</a>');
}
console.log(Text);
回答by s4y
I agree with Jason that it'd be faster/safer to use an existing Markdown library, but you're looking for String.prototype.replace(also, use RegExp literals!):
我同意 Jason 的观点,使用现有的 Markdown 库会更快/更安全,但您正在寻找String.prototype.replace(另外,使用 RegExp 文字!):
var Text = "[Text Example][1]\n[1][http: //www.example.com]";
var rePattern = /\[(.+?)\]\[([0-9]+)\]/gi;
console.log(Text.replace(rePattern, function(match, text, urlId) {
// return an appropriately-formatted link
return `<a href="${urlId}">${text}</a>`;
}));
回答by Vasyl Gutnyk
Here we're using execmethod, it helps to get all matches (with help while loop) and get position of matched string.
这里我们使用 exec方法,它有助于获取所有匹配项(借助 while 循环)并获取匹配字符串的位置。
var input = "A 3 numbers in 333";
var regExp = /\b(\d+)\b/g, match;
while (match = regExp.exec(input))
console.log("Found", match[1], "at", match.index);
// → Found 3 at 2 // Found 333 at 15
回答by Mario Vázquez
Another way to iterate over all matches without relying on exec and match subtleties, is using the string replace function using the regex as the first parameter and a function as the second one. When used like this, the function argument receives the whole match as the first parameter, the grouped matches as next parameters and the index as the last one:
另一种不依赖 exec 和 match 微妙之处迭代所有匹配项的方法是使用字符串替换函数,使用正则表达式作为第一个参数,使用一个函数作为第二个参数。像这样使用时,函数参数接收整个匹配作为第一个参数,分组匹配作为下一个参数,索引作为最后一个:
var text = "[Text Example][1]\n[1][http: //www.example.com]";
// Find resource links
var arrMatch = null;
var rePattern = new RegExp("\[(.+?)\]\[([0-9]+)\]", "gi");
text.replace(rePattern, function(match, g1, g2, index){
// Do whatever
})
You can even iterate over all groups of each match using the global JS variable arguments
, excluding the first and last ones.
您甚至可以使用全局 JS 变量迭代每个匹配项的所有组arguments
,不包括第一个和最后一个。
回答by Ruslan López
Here's somw small example I hope you can find useful.
\number
is used in regex to refer a group match number and $number
is used in the replace function to refer group results so you can enforce that numbers will be the same with something like that if your text is
这是一些小例子,希望你能找到有用的。
\number
在正则表达式中用于引用组匹配编号并$number
在替换函数中用于引用组结果,因此您可以强制数字与类似的内容相同,如果您的文本是
[Text Example][1]\n[1][http://www.example.com]
it will match and if it is
它会匹配,如果是
[Text Example][1]\n[2][http://www.example.com]
it won't
它不会
var re = /\[(.+?)\]\[([0-9]+)\s*.*\s*\[()\]\[(.+?)\]/gi;
var str = '[Text Example][1]\n[1][http://www.example.com]';
var subst = '<a href=""></a>';
var result = str.replace(re, subst);
console.log(result);
回答by Jason McCreary
This format is based on Markdown. There are several JavaScript portsavailable. If you don't want the whole syntax, then I recommend stealingthe portions related to links.
这种格式基于Markdown。有几个可用的JavaScript 端口。如果您不想要整个语法,那么我建议您窃取与链接相关的部分。