我有以下字符串:
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
我希望找到match
后跟red
一词的所有match
个字词,直到下一个match
出现。在这种情况下,应找到第2,第4和第7 EditText
。
如何使用javascript regexp完成此操作?
答案 0 :(得分:1)
首先想到的是:首先将字符串拆分为以"匹配"开头的块。然后,看到哪些块满足条件"后面跟着" red"
,这是非常明显的。使用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]"
答案 1 :(得分:0)
这样的事情有帮助吗?它使用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);
}
输出
Found match at character 19
Found match at character 60
Found match at character 120