github.com/google/osv-scalibr@v0.4.1/extractor/filesystem/internal/regex_helpers_test.go (about) 1 // Copyright 2025 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package internal 16 17 import ( 18 "regexp" 19 "testing" 20 21 "github.com/google/go-cmp/cmp" 22 ) 23 24 func TestMatchCaptureGroups(t *testing.T) { 25 tests := []struct { 26 name string 27 input string 28 pattern string 29 want map[string]string 30 }{ 31 { 32 name: "go-case", 33 input: "match this thing", 34 pattern: `(?P<name>match).*(?P<version>thing)`, 35 want: map[string]string{ 36 "name": "match", 37 "version": "thing", 38 }, 39 }, 40 { 41 name: "only matches the first instance", 42 input: "match this thing batch another think", 43 pattern: `(?P<name>[mb]atch).*?(?P<version>thin[gk])`, 44 want: map[string]string{ 45 "name": "match", 46 "version": "thing", 47 }, 48 }, 49 { 50 name: "nested capture groups", 51 input: "cool something to match against", 52 pattern: `((?P<name>match) (?P<version>against))`, 53 want: map[string]string{ 54 "name": "match", 55 "version": "against", 56 }, 57 }, 58 { 59 name: "nested optional capture groups", 60 input: "cool something to match against", 61 pattern: `((?P<name>match) (?P<version>against))?`, 62 want: map[string]string{ 63 "name": "match", 64 "version": "against", 65 }, 66 }, 67 { 68 name: "nested optional capture groups with larger match", 69 input: "cool something to match against match never", 70 pattern: `.*?((?P<name>match) (?P<version>(against|never)))?`, 71 want: map[string]string{ 72 "name": "match", 73 "version": "against", 74 }, 75 }, 76 } 77 78 for _, test := range tests { 79 t.Run(test.name, func(t *testing.T) { 80 got := MatchNamedCaptureGroups(regexp.MustCompile(test.pattern), test.input) 81 if !cmp.Equal(test.want, got) { 82 t.Errorf("MatchNamedCaptureGroups(%q) = %v, want %v", test.pattern, got, test.want) 83 } 84 }) 85 } 86 }