-
Notifications
You must be signed in to change notification settings - Fork 0
/
capturegroups.go
79 lines (65 loc) · 2.46 KB
/
capturegroups.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package tcg
import (
"fmt"
"regexp"
"strings"
)
func captureGroupsEncode(pre_pattern string, capture_groups []int, pattern, input string) string {
matchedPrePatternCaptureGroups := matchGroupsByNumber(pre_pattern, capture_groups, input)
fpeInput := computeFpeInput(matchedPrePatternCaptureGroups, pattern)
return fpeEncode(pattern, fpeInput)
//fmt.Printf("pre_pattern %s, capture_groups: %v, pattern: %s, input: %s, matched groups:%v, fpeInput: %s\n",
// pre_pattern, capture_groups, pattern, input, matchedPrePatternCaptureGroups, fpeInput )
}
// computeFpeInput constructs a string that when matched to 'pattern' the resulting matching groups
// are the same as 'groupValues'.
func computeFpeInput(groupValues []string, pattern string) string {
patternGroupIndices := findGroupIndices(pattern)
if len(groupValues) != len(patternGroupIndices) {
panic("number of groups in 'pattern' must match that of 'capture_groups'")
}
var input strings.Builder
patternIndex := 0
for group, groupIndices := range patternGroupIndices {
start, end := groupIndices[0], groupIndices[1]
if patternIndex < start {
// Copy everything before the opening paren
input.WriteString(pattern[patternIndex:start])
}
// Copy the capture group value
input.WriteString(groupValues[group])
patternIndex = end;
}
if patternIndex < len(pattern) {
input.WriteString(pattern[patternIndex:])
}
return input.String()
}
// `(\d\d)-(\d\d)`
// []
func findGroupIndices(pattern string) [][]int {
// This is a toy implementation.
// Is there a reliable way to implement this function?
re := regexp.MustCompile(`(\([^\(]*\))`) // `(\(xxxx\))`) // where xxxx is [^\(]
return re.FindAllStringIndex(pattern, -1)
}
// matchGroupsByNumber returns a map where the key is the group number, and the value is the matched substring
// For example: matchGroupsByNumber(`(\d\d)-(\d\d)-(\d\d)`, []int{1,3}, "12-34-56")
// ["12","56"]
func matchGroupsByNumber(pre_pattern string, capture_groups []int, input string) []string {
preRegexp := regexp.MustCompile(pre_pattern)
submatches := preRegexp.FindAllStringSubmatchIndex(input, -1)
if len(submatches) != 1 {
panic("Expected a single set of submatches")
}
var result []string
for _, cg := range capture_groups {
start := submatches[0][2 + 2*(cg-1)]
end := submatches[0][3 + 2*(cg-1)]
if start == -1 || end == -1 {
panic(fmt.Sprintf("Required group not found: %d", cg))
}
result = append(result, string(input[start:end]))
}
return result
}