如果我在字符串中搜索匹配到两个或更多子regexen的联合的正则表达式,有没有办法确定哪个子正则表达式匹配而不单独检查它们?
例如,如果我有代码:
var regExp = new RegExp('ab|cd');
var matches = regExp.allMatches('absolutely fabulous');
搜索会返回两个匹配项 - 但有没有办法让我知道哪个匹配对应哪个子正则表达式?
答案 0 :(得分:0)
通过搜索分支找到答案。
var regExp = new RegExp('(ab)|(cd)'); //brackets are significant
var matches = regExp.allMatches('absolutely fabulous');
var m1 = match.first;
print(m1.group(1)); // 'ab'
print(m1.group(2)); // null, since second term (cd) not matched here
var m2 = match.last;
print(m2.group(1)); // null, since first pattern not matched here
print(m2.group(2)): // 'ac'