Skip to content

Commit dcfd826

Browse files
CIAvashalecthomas
authored andcommitted
Add support for named capture groups
1 parent 15f2498 commit dcfd826

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

Diff for: regexp.go

+11-4
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,8 @@ type LexerState struct {
258258
Rule int
259259
// Group matches.
260260
Groups []string
261+
// Named Group matches.
262+
NamedGroups map[string]string
261263
// Custum context for mutators.
262264
MutatorContext map[interface{}]interface{}
263265
iteratorStack []Iterator
@@ -301,7 +303,7 @@ func (l *LexerState) Iterator() Token { // nolint: gocognit
301303
if !ok {
302304
panic("unknown state " + l.State)
303305
}
304-
ruleIndex, rule, groups := matchRules(l.Text, l.Pos, selectedRule)
306+
ruleIndex, rule, groups, namedGroups := matchRules(l.Text, l.Pos, selectedRule)
305307
// No match.
306308
if groups == nil {
307309
// From Pygments :\
@@ -319,6 +321,7 @@ func (l *LexerState) Iterator() Token { // nolint: gocognit
319321
}
320322
l.Rule = ruleIndex
321323
l.Groups = groups
324+
l.NamedGroups = namedGroups
322325
l.Pos += utf8.RuneCountInString(groups[0])
323326
if rule.Mutator != nil {
324327
if err := rule.Mutator.Mutate(l); err != nil {
@@ -490,18 +493,22 @@ func (r *RegexLexer) Tokenise(options *TokeniseOptions, text string) (Iterator,
490493
return state.Iterator, nil
491494
}
492495

493-
func matchRules(text []rune, pos int, rules []*CompiledRule) (int, *CompiledRule, []string) {
496+
func matchRules(text []rune, pos int, rules []*CompiledRule) (int, *CompiledRule, []string, map[string]string) {
494497
for i, rule := range rules {
495498
match, err := rule.Regexp.FindRunesMatchStartingAt(text, pos)
496499
if match != nil && err == nil && match.Index == pos {
497500
groups := []string{}
501+
namedGroups := map[string]string{}
498502
for _, g := range match.Groups() {
503+
if g.Name != `` {
504+
namedGroups[g.Name] = g.String()
505+
}
499506
groups = append(groups, g.String())
500507
}
501-
return i, rule, groups
508+
return i, rule, groups, namedGroups
502509
}
503510
}
504-
return 0, &CompiledRule{}, nil
511+
return 0, &CompiledRule{}, nil, nil
505512
}
506513

507514
// replace \r and \r\n with \n

0 commit comments

Comments
 (0)