Reputation: 4183
If I search a string for matches to a regex which is the union of two or more sub-regexen, is there any way to determine which sub-regex matches without checking each of them individually?
For example, if I have the code:
var regExp = new RegExp('ab|cd');
var matches = regExp.allMatches('absolutely fabulous');
the search returns two matches - but is there a way for me to know which match corresponds to which sub-regex?
Upvotes: 1
Views: 2053
Reputation: 4183
Found an answer thanks to searching for branches.
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'
Other useful info at dart regex matching and get some information from it
Upvotes: 3