I have the following string:
我有以下字符串:
match ddd green dd match ddd red d match ddddddd yellow ddd match dd red ddddddd match dddd blue ddd match ddd yellow d match ddddd red
I want to find all match
words that are followed by the word red
until the next match
occurs. In this case the 2nd, 4th and 7th match
should be found.
我想找到所有匹配单词,后跟单词red,直到下一个匹配发生。在这种情况下,应找到第2,第4和第7场比赛。
How can this be done with javascript regexp?
如何使用javascript regexp完成此操作?
2 个解决方案
#1
1
First thought to respond this is: begin with splitting string into chunks beginning with "match". Then it's totally obvious to see which chunks satisfiy the condition "is followed by "red".
首先想到的是回应:首先将字符串拆分为以“匹配”开头的块。然后,很明显看到哪些块满足条件“后跟”红色“。
The above solution is pretty simple to write in javascript. Something like this:
在javascript中编写上述解决方案非常简单。像这样的东西:
var string = 'match ddd green dd match ddd red d match ddddddd yellow ddd match dd red ddddddd match dddd blue ddd match ddd yellow d match ddddd red',
chiefWord = 'match',
follower = 'red',
chunks = string.split(new RegExp(chiefWord + '\\s+')),
result = [];
for (var i = 0, n = chunks.length; i < n; i++) {
if (chunks[i].indexOf(follower) >= 0) {
result.push(i); // or chunks[i], or any other way to express result
}
}
console.log(result); // reports "[2, 4, 7]"
#2
0
Would something like this help? It uses exec
to mark where those matches are in the string:
这样的事情有帮助吗?它使用exec来标记这些匹配在字符串中的位置:
var regex = /(match) [a-z]+ red/gi
var myArray;
while ((myArray = regex.exec(str)) !== null) {
var msg = 'Found match at character ' + myArray.index;
console.log(msg);
}
OUTPUT
OUTPUT
Found match at character 19
Found match at character 60
Found match at character 120
DEMO
#1
1
First thought to respond this is: begin with splitting string into chunks beginning with "match". Then it's totally obvious to see which chunks satisfiy the condition "is followed by "red".
首先想到的是回应:首先将字符串拆分为以“匹配”开头的块。然后,很明显看到哪些块满足条件“后跟”红色“。
The above solution is pretty simple to write in javascript. Something like this:
在javascript中编写上述解决方案非常简单。像这样的东西:
var string = 'match ddd green dd match ddd red d match ddddddd yellow ddd match dd red ddddddd match dddd blue ddd match ddd yellow d match ddddd red',
chiefWord = 'match',
follower = 'red',
chunks = string.split(new RegExp(chiefWord + '\\s+')),
result = [];
for (var i = 0, n = chunks.length; i < n; i++) {
if (chunks[i].indexOf(follower) >= 0) {
result.push(i); // or chunks[i], or any other way to express result
}
}
console.log(result); // reports "[2, 4, 7]"
#2
0
Would something like this help? It uses exec
to mark where those matches are in the string:
这样的事情有帮助吗?它使用exec来标记这些匹配在字符串中的位置:
var regex = /(match) [a-z]+ red/gi
var myArray;
while ((myArray = regex.exec(str)) !== null) {
var msg = 'Found match at character ' + myArray.index;
console.log(msg);
}
OUTPUT
OUTPUT
Found match at character 19
Found match at character 60
Found match at character 120
DEMO