-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathregex_test.go
More file actions
1249 lines (1131 loc) · 30.2 KB
/
regex_test.go
File metadata and controls
1249 lines (1131 loc) · 30.2 KB
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package coregex
import (
"reflect"
"regexp"
"testing"
)
// TestCompile tests basic compilation
func TestCompile(t *testing.T) {
tests := []struct {
name string
pattern string
wantErr bool
}{
{"simple literal", "hello", false},
{"digit", `\d`, false},
{"word", `\w+`, false},
{"alternation", "foo|bar", false},
{"repetition", "a+", false},
{"invalid", "(", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re, err := Compile(tt.pattern)
if (err != nil) != tt.wantErr {
t.Errorf("Compile() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !tt.wantErr && re == nil {
t.Error("Compile() returned nil")
}
})
}
}
// TestMustCompile tests panic on invalid pattern
func TestMustCompile(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("MustCompile() did not panic on invalid pattern")
}
}()
MustCompile("(") // Should panic
}
// TestMatch tests Match and MatchString
func TestMatch(t *testing.T) {
tests := []struct {
name string
pattern string
input string
want bool
}{
{"simple match", "hello", "hello world", true},
{"no match", "hello", "goodbye world", false},
{"digit match", `\d`, "age 42", true},
{"digit no match", `\d`, "no digits here", false},
// Note: MVP implementation treats anchors as empty matches
// Full anchor support coming in v1.1
// {"start anchor", "^hello", "hello world", true},
// {"start anchor fail", "^hello", "say hello", false},
{"alternation match", "foo|bar", "test bar end", true},
{"alternation no match", "foo|bar", "test baz end", false},
{"empty pattern", "", "test", true}, // Empty matches
{"empty input", "a", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
// Test Match
got := re.Match([]byte(tt.input))
if got != tt.want {
t.Errorf("Match() = %v, want %v", got, tt.want)
}
// Test MatchString
got = re.MatchString(tt.input)
if got != tt.want {
t.Errorf("MatchString() = %v, want %v", got, tt.want)
}
})
}
}
// TestFind tests Find and FindString
func TestFind(t *testing.T) {
tests := []struct {
name string
pattern string
input string
want string
wantNil bool
}{
{"simple find", "hello", "say hello world", "hello", false},
{"digit find", `\d+`, "age: 42 years", "42", false},
{"no match", "xyz", "abc def", "", true},
{"first of many", "a", "banana", "a", false},
{"empty pattern", "", "test", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
// Test Find
got := re.Find([]byte(tt.input))
if tt.wantNil && got != nil {
t.Errorf("Find() = %q, want nil", got)
}
if !tt.wantNil {
if got == nil {
t.Error("Find() = nil, want match")
return
}
if string(got) != tt.want {
t.Errorf("Find() = %q, want %q", got, tt.want)
}
}
// Test FindString
gotStr := re.FindString(tt.input)
if tt.wantNil && gotStr != "" {
t.Errorf("FindString() = %q, want empty", gotStr)
}
if !tt.wantNil && gotStr != tt.want {
t.Errorf("FindString() = %q, want %q", gotStr, tt.want)
}
})
}
}
// TestFindIndex tests FindIndex and FindStringIndex
func TestFindIndex(t *testing.T) {
tests := []struct {
name string
pattern string
input string
want []int
wantNil bool
}{
{"simple", "hello", "say hello world", []int{4, 9}, false},
{"digit", `\d+`, "age: 42", []int{5, 7}, false},
{"no match", "xyz", "abc", nil, true},
{"start", "hello", "hello world", []int{0, 5}, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
// Test FindIndex
got := re.FindIndex([]byte(tt.input))
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("FindIndex() = %v, want %v", got, tt.want)
}
// Test FindStringIndex
got = re.FindStringIndex(tt.input)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("FindStringIndex() = %v, want %v", got, tt.want)
}
})
}
}
// TestFindAll tests FindAll and FindAllString
func TestFindAll(t *testing.T) {
tests := []struct {
name string
pattern string
input string
n int
want []string
}{
{"find all digits", `\d`, "a1b2c3", -1, []string{"1", "2", "3"}},
{"find limited", `\d`, "a1b2c3", 2, []string{"1", "2"}},
{"find zero", `\d`, "a1b2c3", 0, nil},
{"no matches", `\d`, "abc", -1, nil},
{"find words", `\w+`, "hello world test", -1, []string{"hello", "world", "test"}},
{"find one", `hello`, "hello world hello", 1, []string{"hello"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
// Test FindAll
got := re.FindAll([]byte(tt.input), tt.n)
var gotStr []string
if len(got) > 0 {
gotStr = make([]string, 0, len(got))
for _, m := range got {
gotStr = append(gotStr, string(m))
}
}
if !reflect.DeepEqual(gotStr, tt.want) {
t.Errorf("FindAll() = %v, want %v", gotStr, tt.want)
}
// Test FindAllString
gotStrDirect := re.FindAllString(tt.input, tt.n)
if !reflect.DeepEqual(gotStrDirect, tt.want) {
t.Errorf("FindAllString() = %v, want %v", gotStrDirect, tt.want)
}
})
}
}
// TestString tests the String method
func TestString(t *testing.T) {
pattern := `\d+`
re := MustCompile(pattern)
got := re.String()
if got != pattern {
t.Errorf("String() = %q, want %q", got, pattern)
}
}
// TestRealWorldPatterns tests realistic regex patterns
func TestRealWorldPatterns(t *testing.T) {
tests := []struct {
name string
pattern string
input string
want string
}{
{
name: "email simple",
pattern: `\w+@\w+\.\w+`,
input: "Contact: user@example.com for info",
want: "user@example.com",
},
{
name: "phone number",
pattern: `\d{3}-\d{4}`,
input: "Call 555-1234 today",
want: "555-1234",
},
{
name: "URL protocol",
pattern: `https?://`,
input: "Visit https://example.com",
want: "https://",
},
{
name: "hex color",
pattern: `#[0-9a-fA-F]{6}`,
input: "Background: #FF5733",
want: "#FF5733",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
got := re.FindString(tt.input)
if got != tt.want {
t.Errorf("FindString() = %q, want %q", got, tt.want)
}
})
}
}
// TestEdgeCases tests edge cases
func TestEdgeCases(t *testing.T) {
tests := []struct {
name string
pattern string
input string
want bool
}{
{"empty pattern empty input", "", "", true},
{"empty pattern non-empty input", "", "test", true},
{"non-empty pattern empty input", "a", "", false},
{"unicode", "世界", "你好世界", true},
{"very long input", "needle", string(make([]byte, 10000)) + "needle", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
got := re.MatchString(tt.input)
if got != tt.want {
t.Errorf("MatchString() = %v, want %v", got, tt.want)
}
})
}
}
// TestEndAnchor tests patterns with $ anchor
// Regression test for issue #24: first-call bug with ReverseAnchored patterns
func TestEndAnchor(t *testing.T) {
tests := []struct {
name string
pattern string
input string
want bool
}{
// Basic end anchor
{"a$ matches ending with a", "a$", "ba", true},
{"a$ not matches ending with b", "a$", "ab", false},
{"a$ matches single a", "a$", "a", true},
{"a$ not matches single b", "a$", "b", false},
// Empty string handling
{"^$ matches empty", "^$", "", true},
{"^$ not matches non-empty", "^$", "a", false},
{"$ matches at end of abc", "$", "abc", true},
// Multiple calls should give consistent results (regression for #24)
{"a$ on ab consistent 1", "a$", "ab", false},
{"a$ on ab consistent 2", "a$", "ab", false},
{"a$ on ba consistent 1", "a$", "ba", true},
{"a$ on ba consistent 2", "a$", "ba", true},
// Start anchor combinations
{"^a$ full match a", "^a$", "a", true},
{"^a$ not matches ab", "^a$", "ab", false},
{"^a$ not matches ba", "^a$", "ba", false},
// Alternation with anchors
{"^a?$|^b?$ matches empty", "^a?$|^b?$", "", true},
{"^a?$|^b?$ matches a", "^a?$|^b?$", "a", true},
{"^a?$|^b?$ matches b", "^a?$|^b?$", "b", true},
{"^a?$|^b?$ not matches ab", "^a?$|^b?$", "ab", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
// Call multiple times to catch first-call bugs
for i := 0; i < 3; i++ {
got := re.MatchString(tt.input)
if got != tt.want {
t.Errorf("MatchString() call %d = %v, want %v", i+1, got, tt.want)
}
}
})
}
}
// BenchmarkCompile benchmarks compilation
func BenchmarkCompile(b *testing.B) {
patterns := []string{
"hello",
`\d+`,
`\w+@\w+\.\w+`,
"(foo|bar|baz)",
}
for _, pattern := range patterns {
b.Run(pattern, func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, err := Compile(pattern)
if err != nil {
b.Fatal(err)
}
}
})
}
}
// BenchmarkMatch benchmarks matching
func BenchmarkMatch(b *testing.B) {
re := MustCompile(`\d+`)
input := []byte("the year is 2024")
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
if !re.Match(input) {
b.Fatal("expected match")
}
}
}
// BenchmarkFind benchmarks finding
func BenchmarkFind(b *testing.B) {
tests := []struct {
name string
pattern string
input string
}{
{"literal", "hello", "this is a hello world test string with more text"},
{"digit", `\d+`, "age: 42 years old"},
{"alternation", "foo|bar|baz", "prefix foo middle bar suffix baz end"},
{"word", `\w+`, "hello world test"},
}
for _, tt := range tests {
b.Run(tt.name, func(b *testing.B) {
b.ReportAllocs()
re := MustCompile(tt.pattern)
input := []byte(tt.input)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
match := re.Find(input)
if match == nil {
b.Fatal("expected match")
}
}
})
}
}
// BenchmarkFindAll benchmarks finding all matches
func BenchmarkFindAll(b *testing.B) {
re := MustCompile(`\d`)
input := []byte("1a2b3c4d5e6f7g8h9i0")
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
matches := re.FindAll(input, -1)
if len(matches) != 10 {
b.Fatalf("expected 10 matches, got %d", len(matches))
}
}
}
// BenchmarkFindIndex benchmarks FindIndex operations
func BenchmarkFindIndex(b *testing.B) {
tests := []struct {
name string
pattern string
input []byte
}{
{"literal", "fox", []byte("the quick brown fox jumps")},
{"digit", `\d+`, []byte("abc123def456")},
{"word", `\w+`, []byte("hello, world!")},
// GoAWK pattern (Ben Hoyt) - critical for small string performance
{"goawk_char_range", `j[a-z]+p`, []byte("The quick brown fox jumps over the lazy dog")},
}
for _, tt := range tests {
re := MustCompile(tt.pattern)
b.Run(tt.name, func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.FindIndex(tt.input)
}
})
}
}
// BenchmarkFindAllIndex benchmarks FindAllIndex operations
func BenchmarkFindAllIndex(b *testing.B) {
re := MustCompile(`\w+`)
input := []byte("the quick brown fox jumps over the lazy dog")
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.FindAllIndex(input, -1)
}
}
// BenchmarkFindAllIndex_CharClass benchmarks CharClassSearcher pattern vs stdlib
func BenchmarkFindAllIndex_CharClass(b *testing.B) {
// Generate 1KB input with ~100 word matches
input := make([]byte, 1024)
for i := range input {
if i%10 < 5 {
input[i] = 'a' + byte(i%26)
} else {
input[i] = ' '
}
}
b.Run("coregex/1KB", func(b *testing.B) {
re := MustCompile(`\w+`)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.FindAllIndex(input, -1)
}
})
b.Run("stdlib/1KB", func(b *testing.B) {
re := regexp.MustCompile(`\w+`)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.FindAllIndex(input, -1)
}
})
}
// BenchmarkFindSubmatch benchmarks capture group extraction
func BenchmarkFindSubmatch(b *testing.B) {
tests := []struct {
name string
pattern string
input []byte
}{
{"simple", `(\w+)\s+(\w+)`, []byte("hello world")},
{"email", `(\w+)@(\w+)\.(\w+)`, []byte("user@example.com")},
{"nested", `([a-z]+)(\d+)`, []byte("abc123")},
}
for _, tt := range tests {
re := MustCompile(tt.pattern)
b.Run(tt.name, func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.FindSubmatch(tt.input)
}
})
}
}
// BenchmarkSplit benchmarks Split operations
func BenchmarkSplit(b *testing.B) {
tests := []struct {
name string
pattern string
input string
}{
{"comma", ",", "a,b,c,d,e,f,g,h,i,j"},
{"whitespace", `\s+`, "the quick brown fox jumps"},
{"digit", `\d`, "a1b2c3d4e5"},
}
for _, tt := range tests {
re := MustCompile(tt.pattern)
b.Run(tt.name, func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.Split(tt.input, -1)
}
})
}
}
// BenchmarkReplaceAll benchmarks ReplaceAll operations
func BenchmarkReplaceAll(b *testing.B) {
tests := []struct {
name string
pattern string
input []byte
replacement []byte
}{
{"simple", "[aeiou]", []byte("hello world"), []byte("X")},
{"word", `\w+`, []byte("foo bar baz"), []byte("X")},
{"capture", `(\w+)`, []byte("hello world"), []byte("[$1]")},
}
for _, tt := range tests {
re := MustCompile(tt.pattern)
b.Run(tt.name, func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.ReplaceAll(tt.input, tt.replacement)
}
})
}
}
// BenchmarkReplaceAllFunc benchmarks ReplaceAllFunc operations
func BenchmarkReplaceAllFunc(b *testing.B) {
re := MustCompile(`\w+`)
input := []byte("hello world foo bar")
toUpper := func(match []byte) []byte {
result := make([]byte, len(match))
for i, c := range match {
if c >= 'a' && c <= 'z' {
result[i] = c - 32
} else {
result[i] = c
}
}
return result
}
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.ReplaceAllFunc(input, toUpper)
}
}
// BenchmarkMatchString benchmarks MatchString (string input)
// Includes patterns from GoAWK benchmarks (Ben Hoyt) for regression testing.
func BenchmarkMatchString(b *testing.B) {
tests := []struct {
name string
pattern string
input string
}{
{"literal", "fox", "the quick brown fox"},
{"digit", `\d+`, "abc123def"},
{"anchored", `^hello`, "hello world"},
{"suffix", `\.txt$`, "document.txt"},
// GoAWK patterns (Ben Hoyt) - critical for small string performance
{"goawk_char_range", `j[a-z]+p`, "The quick brown fox jumps over the lazy dog"},
{"goawk_word", `\w+`, "hello world 123"},
{"goawk_lowercase", `[a-z]+`, "Hello World Test"},
}
for _, tt := range tests {
re := MustCompile(tt.pattern)
b.Run(tt.name, func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.MatchString(tt.input)
}
})
}
}
// BenchmarkLiteral benchmarks literal pattern performance
func BenchmarkLiteral(b *testing.B) {
sizes := []struct {
name string
size int
}{
{"100B", 100},
{"1KB", 1024},
{"10KB", 10 * 1024},
}
for _, size := range sizes {
// Create text with pattern at the end
text := make([]byte, size.size)
for i := range text {
text[i] = byte('a' + (i % 26))
}
copy(text[len(text)-10:], "__hello___")
re := MustCompile("hello")
b.Run(size.name, func(b *testing.B) {
b.SetBytes(int64(size.size))
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.Find(text)
}
})
}
}
// BenchmarkCharClass benchmarks character class patterns
func BenchmarkCharClass(b *testing.B) {
input := []byte("abc123def456ghi789")
patterns := []struct {
name string
re string
}{
{"digit", `\d+`},
{"word", `\w+`},
{"alpha", `[a-z]+`},
}
for _, pat := range patterns {
re := MustCompile(pat.re)
b.Run(pat.name+"/Find", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.Find(input)
}
})
b.Run(pat.name+"/FindAll", func(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
re.FindAll(input, -1)
}
})
}
}
// TestCount tests counting matches
func TestCount(t *testing.T) {
tests := []struct {
name string
pattern string
input string
n int
want int
}{
{"all digits", `\d`, "1 2 3 4 5", -1, 5},
{"limited", `\d`, "1 2 3 4 5", 3, 3},
{"no match", `\d`, "abc", -1, 0},
{"words", `\w+`, "hello world foo", -1, 3},
{"zero limit", `\d`, "123", 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
got := re.Count([]byte(tt.input), tt.n)
if got != tt.want {
t.Errorf("Count() = %d, want %d", got, tt.want)
}
// Also test CountString
gotStr := re.CountString(tt.input, tt.n)
if gotStr != tt.want {
t.Errorf("CountString() = %d, want %d", gotStr, tt.want)
}
})
}
}
// TestFindAllSubmatch tests finding all matches with capture groups
func TestFindAllSubmatch(t *testing.T) {
re := MustCompile(`(\w+)=(\d+)`)
input := []byte("a=1 b=2 c=3")
matches := re.FindAllSubmatch(input, -1)
if len(matches) != 3 {
t.Fatalf("expected 3 matches, got %d", len(matches))
}
// Check first match
if string(matches[0][0]) != "a=1" {
t.Errorf("match[0][0] = %q, want %q", string(matches[0][0]), "a=1")
}
if string(matches[0][1]) != "a" {
t.Errorf("match[0][1] = %q, want %q", string(matches[0][1]), "a")
}
if string(matches[0][2]) != "1" {
t.Errorf("match[0][2] = %q, want %q", string(matches[0][2]), "1")
}
// Check second match
if string(matches[1][0]) != "b=2" {
t.Errorf("match[1][0] = %q, want %q", string(matches[1][0]), "b=2")
}
}
// TestFindAllStringSubmatch tests finding all string matches with capture groups
func TestFindAllStringSubmatch(t *testing.T) {
re := MustCompile(`(\w+)@(\w+)`)
input := "a@b c@d"
matches := re.FindAllStringSubmatch(input, -1)
if len(matches) != 2 {
t.Fatalf("expected 2 matches, got %d", len(matches))
}
// Check first match
if matches[0][0] != "a@b" {
t.Errorf("match[0][0] = %q, want %q", matches[0][0], "a@b")
}
if matches[0][1] != "a" {
t.Errorf("match[0][1] = %q, want %q", matches[0][1], "a")
}
// Check second match
if matches[1][0] != "c@d" {
t.Errorf("match[1][0] = %q, want %q", matches[1][0], "c@d")
}
}
// TestFindAllSubmatchIndex tests index pairs for all matches with captures
func TestFindAllSubmatchIndex(t *testing.T) {
re := MustCompile(`(\w+)=(\d+)`)
input := []byte("a=1 b=2")
indices := re.FindAllSubmatchIndex(input, -1)
if len(indices) != 2 {
t.Fatalf("expected 2 index slices, got %d", len(indices))
}
// First match "a=1" at position 0-3
// Group 0 (entire): 0-3
// Group 1 (a): 0-1
// Group 2 (1): 2-3
if indices[0][0] != 0 || indices[0][1] != 3 {
t.Errorf("indices[0][0:2] = [%d, %d], want [0, 3]", indices[0][0], indices[0][1])
}
}
// TestFindStringSubmatch_DotPlusCapture tests capture groups with .+ (any character) patterns.
// This is a regression test for a bug where .+ in capture groups returned incorrect values.
// The bug was caused by StateSplit not cloning captures, breaking COW semantics.
// See: docs/dev/BUG_REPORT_CAPTURE_GROUPS.md
func TestFindStringSubmatch_DotPlusCapture(t *testing.T) {
tests := []struct {
name string
pattern string
input string
want []string
}{
// Basic .+ capture group tests (the bug scenario)
{
name: "dot_plus_basic",
pattern: `^(.+)-(\d+)$`,
input: "hello-123",
want: []string{"hello-123", "hello", "123"},
},
{
name: "dot_plus_multiple_dashes",
pattern: `^(.+)-(\d+)$`,
input: "a-b-c-123",
want: []string{"a-b-c-123", "a-b-c", "123"},
},
{
name: "dot_plus_path_like",
pattern: `^(.+)-(\d+)$`,
input: "dev-java/pkg-17",
want: []string{"dev-java/pkg-17", "dev-java/pkg", "17"},
},
// Non-greedy .+? tests
{
name: "dot_plus_nongreedy",
pattern: `^(.+?)-(\d+)$`,
input: "hello-123",
want: []string{"hello-123", "hello", "123"},
},
// .* tests (zero or more)
{
name: "dot_star_basic",
pattern: `^(.*)x(\d+)$`,
input: "abcx123",
want: []string{"abcx123", "abc", "123"},
},
{
name: "dot_star_empty",
pattern: `^(.*)x(\d+)$`,
input: "x123",
want: []string{"x123", "", "123"},
},
// Unanchored patterns
{
name: "unanchored_dot_plus",
pattern: `(.+)-(\d+)`,
input: "test-456",
want: []string{"test-456", "test", "456"},
},
{
name: "unanchored_with_prefix",
pattern: `(.+)-(\d+)`,
input: "prefix: foo-789 suffix",
want: []string{"prefix: foo-789", "prefix: foo", "789"},
},
// Different separators (not just dash)
{
name: "dot_plus_colon_separator",
pattern: `^(.+):(\d+)$`,
input: "localhost:8080",
want: []string{"localhost:8080", "localhost", "8080"},
},
{
name: "dot_plus_equals_separator",
pattern: `^(.+)=(\d+)$`,
input: "count=42",
want: []string{"count=42", "count", "42"},
},
// Complex patterns with multiple .+ groups
{
name: "two_dot_plus_groups",
pattern: `^(.+)-(.+)-(\d+)$`,
input: "a-b-123",
want: []string{"a-b-123", "a", "b", "123"},
},
// Explicit character classes (these always worked - control test)
{
name: "char_class_works",
pattern: `^([a-z]+)-(\d+)$`,
input: "hello-123",
want: []string{"hello-123", "hello", "123"},
},
// \w+ (should also work)
{
name: "word_class_pattern",
pattern: `^(\w+)-(\d+)$`,
input: "hello-123",
want: []string{"hello-123", "hello", "123"},
},
// Edge case: single character before separator
{
name: "single_char_before_sep",
pattern: `^(.+)-(\d+)$`,
input: "a-1",
want: []string{"a-1", "a", "1"},
},
// Real-world: version stripping pattern (from GRPM project)
{
name: "version_strip",
pattern: `^(.+)-(\d.*)$`,
input: "dev-java/openjdk-17.0.1",
want: []string{"dev-java/openjdk-17.0.1", "dev-java/openjdk", "17.0.1"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
re := MustCompile(tt.pattern)
got := re.FindStringSubmatch(tt.input)
if !reflect.DeepEqual(got, tt.want) {
t.Errorf("FindStringSubmatch(%q, %q):\n got: %v\n want: %v",
tt.pattern, tt.input, got, tt.want)
}
})
}
}
// TestFindStringSubmatch_DotPlusCapture_StdlibCompatibility verifies that
// FindStringSubmatch matches stdlib regexp behavior for .+ patterns.
func TestFindStringSubmatch_DotPlusCapture_StdlibCompatibility(t *testing.T) {
patterns := []string{
`^(.+)-(\d+)$`,
`^(.+?)-(\d+)$`,
`^(.*)x(\d+)$`,
`(.+)-(\d+)`,
`^(.+):(\d+)$`,
`^(.+)-(.+)-(\d+)$`,
`^(.+)-(\d.*)$`,
}
inputs := []string{
"hello-123",
"a-b-c-456",
"abcx789",
"test-999",
"host:8080",
"a-b-123",
"pkg-1.2.3",
}
for _, pattern := range patterns {
stdRe := regexp.MustCompile(pattern)
cgRe := MustCompile(pattern)
for _, input := range inputs {
stdMatch := stdRe.FindStringSubmatch(input)
cgMatch := cgRe.FindStringSubmatch(input)
if !reflect.DeepEqual(stdMatch, cgMatch) {
t.Errorf("Pattern %q, Input %q:\n stdlib: %v\n coregex: %v",
pattern, input, stdMatch, cgMatch)
}
}
}
}
// TestFindSubmatchIndex_DotPlusCapture tests capture group indices with .+ patterns.
func TestFindSubmatchIndex_DotPlusCapture(t *testing.T) {
re := MustCompile(`^(.+)-(\d+)$`)
input := []byte("hello-123")
indices := re.FindSubmatchIndex(input)
// Expected: [0, 9, 0, 5, 6, 9]
// Group 0 (full match): 0-9 "hello-123"
// Group 1 (.+): 0-5 "hello"
// Group 2 (\d+): 6-9 "123"
want := []int{0, 9, 0, 5, 6, 9}
if !reflect.DeepEqual(indices, want) {
t.Errorf("FindSubmatchIndex():\n got: %v\n want: %v", indices, want)
}
// Verify slices match expected strings
if string(input[indices[0]:indices[1]]) != "hello-123" {
t.Errorf("Group 0: got %q, want %q", string(input[indices[0]:indices[1]]), "hello-123")
}
if string(input[indices[2]:indices[3]]) != "hello" {
t.Errorf("Group 1: got %q, want %q", string(input[indices[2]:indices[3]]), "hello")
}
if string(input[indices[4]:indices[5]]) != "123" {
t.Errorf("Group 2: got %q, want %q", string(input[indices[4]:indices[5]]), "123")
}
}
// TestLongest tests leftmost-longest (POSIX) matching semantics.
// Verifies that Longest() changes alternation behavior from
// leftmost-first (Perl) to leftmost-longest (POSIX).
func TestLongest(t *testing.T) {
tests := []struct {
name string
pattern string
input string
wantDefault string // leftmost-first (Perl)
wantLongest string // leftmost-longest (POSIX)
}{
{
name: "alternation a|ab",
pattern: `(a|ab)`,
input: "ab",
wantDefault: "a",
wantLongest: "ab",
},
{