1
1
mirror of https://github.com/walles/moar.git synced 2024-09-17 15:07:11 +03:00
moar/m/matchRanges.go

44 lines
725 B
Go
Raw Permalink Normal View History

2019-06-29 19:29:37 +03:00
package m
import "regexp"
2019-06-30 10:43:58 +03:00
// MatchRanges collects match indices
type MatchRanges struct {
Matches [][]int
}
2019-06-29 19:29:37 +03:00
// GetMatchRanges locates a regexp in a string
func GetMatchRanges(String *string, Pattern *regexp.Regexp) *MatchRanges {
2019-06-30 10:53:24 +03:00
if Pattern == nil {
return nil
}
2019-06-30 10:43:58 +03:00
return &MatchRanges{
Matches: Pattern.FindAllStringIndex(*String, -1),
2019-06-30 10:43:58 +03:00
}
2019-06-29 19:29:37 +03:00
}
// InRange says true if the index is part of a regexp match
func (mr *MatchRanges) InRange(index int) bool {
if mr == nil {
return false
}
2019-06-30 10:43:58 +03:00
for _, match := range mr.Matches {
matchFirstIndex := match[0]
matchLastIndex := match[1] - 1
if index < matchFirstIndex {
continue
}
if index > matchLastIndex {
continue
}
return true
}
2019-06-29 19:29:37 +03:00
return false
}