Javascript Regex - 查找所有可能的匹配项,即使在已捕获的匹配项中也是如此 [英] Javascript Regex - Find all possible matches, even in already captured matches
问题描述
我正在尝试使用带有javascript的正则表达式从字符串中获取所有可能的匹配。我的方法似乎不匹配已经匹配的字符串部分。
I'm trying to obtain all possible matches from a string using regex with javascript. It appears that my method of doing this is not matching parts of the string that have already been matched.
变量:
var string = 'A1B1Y:A1B2Y:A1B3Y:A1B4Z:A1B5Y:A1B6Y:A1B7Y:A1B8Z:A1B9Y:A1B10Y:A1B11Y';
var reg = /A[0-9]+B[0-9]+Y:A[0-9]+B[0-9]+Y/g;
代码:
var match = string.match(reg);
我得到的所有匹配结果:
All matched results I get:
A1B1Y:A1B2Y
A1B5Y:A1B6Y
A1B9Y:A1B10Y
我想要的匹配结果:
A1B1Y:A1B2Y
A1B2Y:A1B3Y
A1B5Y:A1B6Y
A1B6Y:A1B7Y
A1B9Y:A1B10Y
A1B10Y:A1B11Y
在我看来,我希望 A1B1Y:A1B2Y
与 A1B2Y一起匹配:A1B3Y
,即使字符串中的 A1B2Y
也需要是两场比赛的一部分。
In my head, I want A1B1Y:A1B2Y
to be a match along with A1B2Y:A1B3Y
, even though A1B2Y
in the string will need to be part of two matches.
推荐答案
在不修改正则表达式的情况下,您可以将其设置为在每次匹配后的匹配后半部分开始时使用 .exec
并操纵正则表达式对象的 lastIndex
property。
Without modifying your regex, you can set it to start matching at the beginning of the second half of the match after each match using .exec
and manipulating the regex object's lastIndex
property.
var string = 'A1B1Y:A1B2Y:A1B3Y:A1B4Z:A1B5Y:A1B6Y:A1B7Y:A1B8Z:A1B9Y:A1B10Y:A1B11Y';
var reg = /A[0-9]+B[0-9]+Y:A[0-9]+B[0-9]+Y/g;
var matches = [], found;
while (found = reg.exec(string)) {
matches.push(found[0]);
reg.lastIndex -= found[0].split(':')[1].length;
}
console.log(matches);
//["A1B1Y:A1B2Y", "A1B2Y:A1B3Y", "A1B5Y:A1B6Y", "A1B6Y:A1B7Y", "A1B9Y:A1B10Y", "A1B10Y:A1B11Y"]
根据Bergi的评论,您还可以获得最后一场比赛的索引并将其增加1所以它不会从比赛的后半段开始匹配,而是开始尝试从每场比赛的第二个角色开始匹配:
As per Bergi's comment, you can also get the index of the last match and increment it by 1 so it instead of starting to match from the second half of the match onwards, it will start attempting to match from the second character of each match onwards:
reg.lastIndex = found.index+1;
最终结果是一样的。尽管如此,Bergi的更新代码稍微少一点,而且更快。 =]
The final outcome is the same. Though, Bergi's update has a little less code and performs slightly faster. =]
这篇关于Javascript Regex - 查找所有可能的匹配项,即使在已捕获的匹配项中也是如此的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!