-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathregex.go
More file actions
1678 lines (1529 loc) · 45.4 KB
/
regex.go
File metadata and controls
1678 lines (1529 loc) · 45.4 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 provides a high-performance regex engine for Go.
//
// coregex achieves 5-50x speedup over Go's stdlib regexp through:
// - Multi-engine architecture (NFA, Lazy DFA, prefilters)
// - SIMD-accelerated primitives (memchr, memmem, teddy)
// - Literal extraction and prefiltering
// - Automatic strategy selection
//
// The public API is compatible with stdlib regexp where possible, making it
// easy to migrate existing code.
//
// Basic usage:
//
// // Compile a pattern
// re, err := coregex.Compile(`\d+`)
// if err != nil {
// log.Fatal(err)
// }
//
// // Find first match
// match := re.Find([]byte("hello 123 world"))
// fmt.Println(string(match)) // "123"
//
// // Check if matches
// if re.Match([]byte("hello 123")) {
// fmt.Println("matched!")
// }
//
// Advanced usage:
//
// // Custom configuration
// config := coregex.DefaultConfig()
// config.MaxDFAStates = 50000
// re, err := coregex.CompileWithConfig("(a|b|c)*", config)
//
// Performance characteristics:
// - Patterns with literals: 5-50x faster (prefilter optimization)
// - Simple patterns: comparable to stdlib
// - Complex patterns: 2-10x faster (DFA avoids backtracking)
// - Worst case: guaranteed O(m*n) (ReDoS safe)
//
// Limitations (v1.0):
// - No capture groups (coming in v1.1)
// - No replace functions (coming in v1.1)
// - No multiline/case-insensitive flags (coming in v1.1)
package coregex
import (
"io"
"iter"
"regexp/syntax"
"strings"
"unsafe"
"github.com/coregx/coregex/meta"
)
// stringToBytes converts string to []byte without allocation.
// This is the Go equivalent of Rust's str.as_bytes() - a zero-cost reinterpret cast.
// The returned slice MUST NOT be modified (same as Rust's immutable &[u8]).
//
//go:inline
func stringToBytes(s string) []byte {
if s == "" {
return nil
}
// G103: Safe - read-only view of immutable string data (like Rust's as_bytes)
return unsafe.Slice(unsafe.StringData(s), len(s)) //nolint:gosec
}
// Regex represents a compiled regular expression.
//
// A Regex is safe to use concurrently from multiple goroutines, except for
// methods that modify internal state (like ResetStats).
//
// Example:
//
// re := coregex.MustCompile(`hello`)
// if re.Match([]byte("hello world")) {
// println("matched!")
// }
type Regex struct {
engine *meta.Engine
pattern string
longest bool // if true, prefer leftmost-longest match (POSIX semantics)
}
// Regexp is an alias for Regex to provide drop-in compatibility with stdlib regexp.
// This allows replacing `import "regexp"` with `import regexp "github.com/coregx/coregex"`
// without changing type names in existing code.
//
// Example:
//
// import regexp "github.com/coregx/coregex"
//
// var re *regexp.Regexp = regexp.MustCompile(`\d+`)
type Regexp = Regex
// Compile compiles a regular expression pattern.
//
// Syntax is Perl-compatible (same as Go's stdlib regexp).
// Returns an error if the pattern is invalid.
//
// Example:
//
// re, err := coregex.Compile(`\d{3}-\d{4}`)
// if err != nil {
// log.Fatal(err)
// }
func Compile(pattern string) (*Regex, error) {
engine, err := meta.Compile(pattern)
if err != nil {
return nil, err
}
return &Regex{
engine: engine,
pattern: pattern,
}, nil
}
// MustCompile compiles a regular expression pattern and panics if it fails.
//
// This is useful for patterns known to be valid at compile time.
//
// Example:
//
// var emailRegex = coregex.MustCompile(`[a-z]+@[a-z]+\.[a-z]+`)
func MustCompile(pattern string) *Regex {
re, err := Compile(pattern)
if err != nil {
panic("regexp: Compile(`" + pattern + "`): " + err.Error())
}
return re
}
// CompilePOSIX is like Compile but restricts the regular expression to
// POSIX ERE (egrep) syntax and changes the match semantics to leftmost-longest.
//
// That is, when matching against text, the regexp returns a match that
// begins as early as possible in the input (leftmost), and among those
// it chooses a match that is as long as possible.
// This so-called leftmost-longest matching is the same semantics
// that early regular expression implementations used and that POSIX
// specifies.
func CompilePOSIX(pattern string) (*Regex, error) {
re, err := Compile(pattern)
if err != nil {
return nil, err
}
re.Longest()
return re, nil
}
// MustCompilePOSIX is like CompilePOSIX but panics if the expression cannot
// be parsed.
// It simplifies safe initialization of global variables holding compiled
// regular expressions.
func MustCompilePOSIX(pattern string) *Regex {
re, err := CompilePOSIX(pattern)
if err != nil {
panic("regexp: CompilePOSIX(`" + pattern + "`): " + err.Error())
}
return re
}
// Match reports whether the byte slice b contains any match of the regular
// expression pattern.
// More complicated queries need to use Compile and the full Regexp interface.
func Match(pattern string, b []byte) (matched bool, err error) {
re, err := Compile(pattern)
if err != nil {
return false, err
}
return re.Match(b), nil
}
// MatchString reports whether the string s contains any match of the regular
// expression pattern.
// More complicated queries need to use Compile and the full Regexp interface.
func MatchString(pattern string, s string) (matched bool, err error) {
re, err := Compile(pattern)
if err != nil {
return false, err
}
return re.MatchString(s), nil
}
// CompileWithConfig compiles a pattern with custom configuration.
//
// This allows fine-tuning of performance characteristics.
//
// Example:
//
// config := coregex.DefaultConfig()
// config.MaxDFAStates = 100000 // Larger cache
// re, err := coregex.CompileWithConfig("(a|b|c)*", config)
func CompileWithConfig(pattern string, config meta.Config) (*Regex, error) {
engine, err := meta.CompileWithConfig(pattern, config)
if err != nil {
return nil, err
}
return &Regex{
engine: engine,
pattern: pattern,
}, nil
}
// DefaultConfig returns the default configuration for compilation.
//
// Users can customize this and pass to CompileWithConfig.
//
// Example:
//
// config := coregex.DefaultConfig()
// config.EnableDFA = false // Use NFA only
// re, _ := coregex.CompileWithConfig("pattern", config)
func DefaultConfig() meta.Config {
return meta.DefaultConfig()
}
// QuoteMeta returns a string that escapes all regular expression metacharacters
// inside the argument text; the returned string is a regular expression matching
// the literal text.
//
// Example:
//
// escaped := coregex.QuoteMeta("hello.world")
// // escaped = "hello\\.world"
// re := coregex.MustCompile(escaped)
// re.MatchString("hello.world") // true
func QuoteMeta(s string) string {
// Special characters that need escaping in regex
const special = `\.+*?()|[]{}^$`
// Count how many characters need escaping
n := 0
for i := 0; i < len(s); i++ {
if isSpecial(s[i], special) {
n++
}
}
// If no escaping needed, return original
if n == 0 {
return s
}
// Build escaped string
buf := make([]byte, len(s)+n)
j := 0
for i := 0; i < len(s); i++ {
if isSpecial(s[i], special) {
buf[j] = '\\'
j++
}
buf[j] = s[i]
j++
}
return string(buf)
}
// isSpecial returns true if c is in the special characters string.
func isSpecial(c byte, special string) bool {
for i := 0; i < len(special); i++ {
if c == special[i] {
return true
}
}
return false
}
// Match reports whether the byte slice b contains any match of the pattern.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// if re.Match([]byte("hello 123")) {
// println("contains digits")
// }
func (r *Regex) Match(b []byte) bool {
return r.engine.IsMatch(b)
}
// MatchString reports whether the string s contains any match of the pattern.
// This is a zero-allocation operation (like Rust's is_match).
//
// Example:
//
// re := coregex.MustCompile(`hello`)
// if re.MatchString("hello world") {
// println("matched!")
// }
func (r *Regex) MatchString(s string) bool {
return r.engine.IsMatch(stringToBytes(s))
}
// Find returns a slice holding the text of the leftmost match in b.
// Returns nil if no match is found.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// match := re.Find([]byte("age: 42"))
// println(string(match)) // "42"
func (r *Regex) Find(b []byte) []byte {
// Use zero-allocation FindIndices internally
start, end, found := r.engine.FindIndices(b)
if !found {
return nil
}
return b[start:end]
}
// FindString returns a string holding the text of the leftmost match in s.
// Returns empty string if no match is found.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// match := re.FindString("age: 42")
// println(match) // "42"
func (r *Regex) FindString(s string) string {
b := stringToBytes(s)
start, end, found := r.engine.FindIndices(b)
if !found {
return ""
}
return s[start:end] // Return substring of original string - no allocation for input
}
// FindIndex returns a two-element slice of integers defining the location of
// the leftmost match in b. The match is at b[loc[0]:loc[1]].
// Returns nil if no match is found.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// loc := re.FindIndex([]byte("age: 42"))
// println(loc[0], loc[1]) // 5, 7
func (r *Regex) FindIndex(b []byte) []int {
// Use zero-allocation FindIndices internally
start, end, found := r.engine.FindIndices(b)
if !found {
return nil
}
return []int{start, end}
}
// FindStringIndex returns a two-element slice of integers defining the location
// of the leftmost match in s. The match is at s[loc[0]:loc[1]].
// Returns nil if no match is found.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// loc := re.FindStringIndex("age: 42")
// println(loc[0], loc[1]) // 5, 7
func (r *Regex) FindStringIndex(s string) []int {
start, end, found := r.engine.FindIndices(stringToBytes(s))
if !found {
return nil
}
return []int{start, end}
}
// FindAll returns a slice of all successive matches of the pattern in b.
// If n > 0, it returns at most n matches. If n <= 0, it returns all matches.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// matches := re.FindAll([]byte("1 2 3"), -1)
// // matches = [[]byte("1"), []byte("2"), []byte("3")]
func (r *Regex) FindAll(b []byte, n int) [][]byte {
if n == 0 {
return nil
}
// Ultra-fast path: start-anchored patterns (^) with first-byte rejection.
// Avoids entire dispatch chain for the common no-match case.
if r.engine.IsStartAnchoredWithFirstByteReject(b) {
return nil
}
// Use optimized streaming path for ALL strategies (state-reusing, no sync.Pool overhead)
return r.findAllStreaming(b, n)
}
// findAllStreaming uses state-reusing search loop for all strategies.
// This avoids sync.Pool overhead (1.29M Get/Put → 1 for 6MB input).
func (r *Regex) findAllStreaming(b []byte, n int) [][]byte {
// Get streaming indices ([][2]int format)
streamResults := r.engine.FindAllIndicesStreaming(b, n, nil)
if len(streamResults) == 0 {
return nil
}
// Convert indices to byte slices
matches := make([][]byte, len(streamResults))
for i, m := range streamResults {
matches[i] = b[m[0]:m[1]]
}
return matches
}
// FindAllString returns a slice of all successive matches of the pattern in s.
// If n > 0, it returns at most n matches. If n <= 0, it returns all matches.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// matches := re.FindAllString("1 2 3", -1)
// // matches = ["1", "2", "3"]
func (r *Regex) FindAllString(s string, n int) []string {
b := stringToBytes(s)
matches := r.FindAll(b, n)
if matches == nil {
return nil
}
result := make([]string, len(matches))
for i, m := range matches {
if len(m) == 0 {
result[i] = ""
} else {
// G103: Safe pointer arithmetic to compute substring offset within same backing array
start := int(uintptr(unsafe.Pointer(&m[0])) - uintptr(unsafe.Pointer(&b[0]))) //nolint:gosec
result[i] = s[start : start+len(m)]
}
}
return result
}
// String returns the source text used to compile the regular expression.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// println(re.String()) // `\d+`
func (r *Regex) String() string {
return r.pattern
}
// Longest makes future searches prefer the leftmost-longest match.
//
// By default, coregex uses leftmost-first (Perl) semantics where the first
// alternative in an alternation wins. After calling Longest(), coregex uses
// leftmost-longest (POSIX) semantics where the longest match wins.
//
// Example:
//
// re := coregex.MustCompile(`(a|ab)`)
// re.FindString("ab") // returns "a" (leftmost-first: first branch wins)
//
// re.Longest()
// re.FindString("ab") // returns "ab" (leftmost-longest: longest wins)
//
// Note: Unlike stdlib, calling Longest() modifies the regex state and should
// not be called concurrently with search methods.
func (r *Regex) Longest() {
r.longest = true
r.engine.SetLongest(true)
}
// LiteralPrefix returns a literal string that must begin any match of the
// regular expression re. It returns the boolean true if the literal string
// comprises the entire regular expression.
//
// Example:
//
// re := coregex.MustCompile(`Hello, \w+`)
// prefix, complete := re.LiteralPrefix()
// // prefix = "Hello, ", complete = false
//
// re2 := coregex.MustCompile(`Hello`)
// prefix2, complete2 := re2.LiteralPrefix()
// // prefix2 = "Hello", complete2 = true
func (r *Regex) LiteralPrefix() (prefix string, complete bool) {
re, err := syntax.Parse(r.pattern, syntax.Perl)
if err != nil {
return "", false
}
re = re.Simplify()
return literalPrefix(re)
}
// literalPrefix extracts the literal prefix from a parsed regex AST.
func literalPrefix(re *syntax.Regexp) (string, bool) {
switch re.Op {
case syntax.OpLiteral:
return string(re.Rune), true
case syntax.OpConcat:
// Concatenation: collect literal prefixes from the beginning
var prefix []rune
hasAnchor := false
for _, sub := range re.Sub {
switch sub.Op {
case syntax.OpLiteral:
prefix = append(prefix, sub.Rune...)
case syntax.OpCapture:
// Look inside capture group
inner, complete := literalPrefix(sub)
prefix = append(prefix, []rune(inner)...)
if !complete {
return string(prefix), false
}
case syntax.OpBeginLine, syntax.OpEndLine, syntax.OpBeginText, syntax.OpEndText:
// Skip anchors - they don't produce literal characters
// but mark that pattern has anchors (not complete)
hasAnchor = true
continue
case syntax.OpEmptyMatch:
// Empty match doesn't affect prefix
continue
default:
// Non-literal found
return string(prefix), false
}
}
// If we have anchors, the pattern is not "complete" (has additional constraints)
if hasAnchor {
return string(prefix), false
}
return string(prefix), true
case syntax.OpCapture:
// Capture group: look at the contents
if len(re.Sub) == 1 {
return literalPrefix(re.Sub[0])
}
return "", false
case syntax.OpBeginLine, syntax.OpEndLine, syntax.OpBeginText, syntax.OpEndText:
// Anchors alone mean no literal prefix and not complete
return "", false
case syntax.OpEmptyMatch:
return "", true
default:
return "", false
}
}
// NumSubexp returns the number of parenthesized subexpressions in this Regex.
// This does NOT include group 0 (the entire match), matching stdlib regexp behavior.
//
// Example:
//
// re := coregex.MustCompile(`(\w+)@(\w+)\.(\w+)`)
// println(re.NumSubexp()) // 3 (just the capture groups)
func (r *Regex) NumSubexp() int {
// Subtract 1 because NumCaptures() includes group 0 (entire match)
// but NumSubexp should only count parenthesized subexpressions
n := r.engine.NumCaptures() - 1
if n < 0 {
return 0
}
return n
}
// SubexpNames returns the names of the parenthesized subexpressions in this Regex.
// The name for the first sub-expression is names[1], so that if m is a match slice,
// the name for m[i] is SubexpNames()[i].
// Since the Regexp as a whole cannot be named, names[0] is always the empty string.
// The slice returned is shared and must not be modified.
//
// Example:
//
// re := coregex.MustCompile(`(?P<year>\d+)-(?P<month>\d+)`)
// names := re.SubexpNames()
// // names[0] = ""
// // names[1] = "year"
// // names[2] = "month"
func (r *Regex) SubexpNames() []string {
return r.engine.SubexpNames()
}
// SubexpIndex returns the index of the first subexpression with the given name,
// or -1 if there is no subexpression with that name.
//
// Note that multiple subexpressions can be written using the same name, as in
// (?P<bob>a+)(?P<bob>b+), which declares two subexpressions named "bob".
// In this case, SubexpIndex returns the index of the leftmost such subexpression
// in the regular expression.
//
// Example:
//
// re := coregex.MustCompile(`(?P<year>\d+)-(?P<month>\d+)`)
// re.SubexpIndex("year") // returns 1
// re.SubexpIndex("month") // returns 2
// re.SubexpIndex("day") // returns -1
func (r *Regex) SubexpIndex(name string) int {
if name == "" {
return -1
}
names := r.SubexpNames()
for i, n := range names {
if n == name {
return i
}
}
return -1
}
// FindSubmatch returns a slice holding the text of the leftmost match
// and the matches of all capture groups.
//
// A return value of nil indicates no match.
// Result[0] is the entire match, result[i] is the ith capture group.
// Unmatched groups will be nil.
//
// Example:
//
// re := coregex.MustCompile(`(\w+)@(\w+)\.(\w+)`)
// match := re.FindSubmatch([]byte("user@example.com"))
// // match[0] = "user@example.com"
// // match[1] = "user"
// // match[2] = "example"
// // match[3] = "com"
func (r *Regex) FindSubmatch(b []byte) [][]byte {
match := r.engine.FindSubmatch(b)
if match == nil {
return nil
}
return match.AllGroups()
}
// FindStringSubmatch returns a slice of strings holding the text of the leftmost
// match and the matches of all capture groups.
//
// Example:
//
// re := coregex.MustCompile(`(\w+)@(\w+)\.(\w+)`)
// match := re.FindStringSubmatch("user@example.com")
// // match[0] = "user@example.com"
// // match[1] = "user"
func (r *Regex) FindStringSubmatch(s string) []string {
match := r.engine.FindSubmatch(stringToBytes(s))
if match == nil {
return nil
}
return match.AllGroupStrings()
}
// FindSubmatchIndex returns a slice holding the index pairs for the leftmost
// match and the matches of all capture groups.
//
// A return value of nil indicates no match.
// Result[2*i:2*i+2] is the indices for the ith group.
// Unmatched groups have -1 indices.
//
// Example:
//
// re := coregex.MustCompile(`(\w+)@(\w+)\.(\w+)`)
// idx := re.FindSubmatchIndex([]byte("user@example.com"))
// // idx[0:2] = indices for entire match
// // idx[2:4] = indices for first capture group
func (r *Regex) FindSubmatchIndex(b []byte) []int {
match := r.engine.FindSubmatch(b)
if match == nil {
return nil
}
numGroups := match.NumCaptures()
result := make([]int, numGroups*2)
for i := 0; i < numGroups; i++ {
idx := match.GroupIndex(i)
if len(idx) >= 2 {
result[i*2] = idx[0]
result[i*2+1] = idx[1]
} else {
result[i*2] = -1
result[i*2+1] = -1
}
}
return result
}
// FindStringSubmatchIndex returns the index pairs for the leftmost match
// and capture groups. Same as FindSubmatchIndex but for strings.
func (r *Regex) FindStringSubmatchIndex(s string) []int {
return r.FindSubmatchIndex(stringToBytes(s))
}
// FindAllIndex returns a slice of all successive matches of the pattern in b,
// as index pairs [start, end].
// If n > 0, it returns at most n matches. If n <= 0, it returns all matches.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// indices := re.FindAllIndex([]byte("1 2 3"), -1)
// // indices = [[0,1], [2,3], [4,5]]
func (r *Regex) FindAllIndex(b []byte, n int) [][]int {
if n == 0 {
return nil
}
// Use compact [][2]int internally, convert at the boundary.
// This reduces allocations from N+1 (one []int per match) to 2 (one flat buffer + one slice header).
compact := r.engine.FindAllIndicesStreaming(b, n, nil)
return compactToSliceOfSlice(compact)
}
// compactToSliceOfSlice converts [][2]int to [][]int using a flat buffer.
// This reduces allocations from N+1 (one []int heap alloc per match) to exactly 2:
// one flat []int buffer for all indices, one [][]int for slice headers.
// Each result[i] is a length-2/capacity-2 slice into the flat buffer.
func compactToSliceOfSlice(compact [][2]int) [][]int {
if len(compact) == 0 {
return nil
}
buf := make([]int, len(compact)*2)
result := make([][]int, len(compact))
for i, m := range compact {
buf[i*2] = m[0]
buf[i*2+1] = m[1]
result[i] = buf[i*2 : i*2+2 : i*2+2]
}
return result
}
// AppendAllIndex appends all successive match index pairs to dst and returns
// the extended slice. This follows the Go stdlib append pattern (like
// strconv.AppendInt) with dst as the first parameter.
//
// Zero-allocation when dst has sufficient capacity. Unlike FindAllIndex which
// returns [][]int (N heap allocations for N matches), AppendAllIndex uses a
// flat [][2]int layout requiring at most one allocation for the backing array.
//
// If n > 0, it appends at most n matches. If n <= 0, it appends all matches.
// Pass nil as dst for a fresh allocation.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// indices := re.AppendAllIndex(nil, []byte("a1b2c3"), -1)
// // indices = [[1,2], [3,4], [5,6]]
//
// // Reuse buffer across calls:
// buf := make([][2]int, 0, 64)
// buf = re.AppendAllIndex(buf[:0], data1, -1)
// process(buf)
// buf = re.AppendAllIndex(buf[:0], data2, -1)
// process(buf)
func (r *Regex) AppendAllIndex(dst [][2]int, b []byte, n int) [][2]int {
if n == 0 {
return nil
}
return r.engine.FindAllIndicesStreaming(b, n, dst)
}
// AppendAllStringIndex appends all successive match index pairs for the string
// s to dst and returns the extended slice. This is the string version of
// AppendAllIndex.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// indices := re.AppendAllStringIndex(nil, "a1b2c3", -1)
// // indices = [[1,2], [3,4], [5,6]]
func (r *Regex) AppendAllStringIndex(dst [][2]int, s string, n int) [][2]int {
return r.AppendAllIndex(dst, stringToBytes(s), n)
}
// FindAllStringIndex returns a slice of all successive matches of the pattern in s,
// as index pairs [start, end].
// If n > 0, it returns at most n matches. If n <= 0, it returns all matches.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// indices := re.FindAllStringIndex("1 2 3", -1)
// // indices = [[0,1], [2,3], [4,5]]
func (r *Regex) FindAllStringIndex(s string, n int) [][]int {
return r.FindAllIndex(stringToBytes(s), n)
}
// ReplaceAllLiteral returns a copy of src, replacing matches of the pattern
// with the replacement bytes repl.
// The replacement is substituted directly, without expanding $ variables.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// result := re.ReplaceAllLiteral([]byte("age: 42"), []byte("XX"))
// // result = []byte("age: XX")
func (r *Regex) ReplaceAllLiteral(src, repl []byte) []byte {
var result []byte
lastEnd := 0
pos := 0
lastMatchEnd := -1
matched := false
for {
start, end, found := r.engine.FindIndicesAt(src, pos)
if !found {
break
}
// Skip empty matches at the position where a non-empty match just ended.
// This matches Go stdlib behavior (see FindAllIndex for details).
//nolint:gocritic // badCond: intentional - checking empty match at lastMatchEnd
if start == end && start == lastMatchEnd {
pos++
if pos > len(src) {
break
}
continue
}
if !matched {
// Lazy allocation on first match
result = make([]byte, 0, len(src))
matched = true
}
result = append(result, src[lastEnd:start]...)
result = append(result, repl...)
lastEnd = end
if start != end {
lastMatchEnd = end
}
switch {
case start == end:
pos = end + 1
case end > pos:
pos = end
default:
pos++
}
if pos > len(src) {
break
}
}
if !matched {
// No matches: return a copy of src (stdlib compatibility)
out := make([]byte, len(src))
copy(out, src)
return out
}
result = append(result, src[lastEnd:]...)
return result
}
// ReplaceAllLiteralString returns a copy of src, replacing matches of the pattern
// with the replacement string repl.
// The replacement is substituted directly, without expanding $ variables.
//
// Example:
//
// re := coregex.MustCompile(`\d+`)
// result := re.ReplaceAllLiteralString("age: 42", "XX")
// // result = "age: XX"
func (r *Regex) ReplaceAllLiteralString(src, repl string) string {
b := stringToBytes(src)
var buf strings.Builder
lastEnd := 0
pos := 0
lastMatchEnd := -1
matched := false
for {
start, end, found := r.engine.FindIndicesAt(b, pos)
if !found {
break
}
//nolint:gocritic // badCond: intentional - checking empty match at lastMatchEnd
if start == end && start == lastMatchEnd {
pos++
if pos > len(src) {
break
}
continue
}
if !matched {
buf.Grow(len(src))
matched = true
}
buf.WriteString(src[lastEnd:start])
buf.WriteString(repl)
lastEnd = end
if start != end {
lastMatchEnd = end
}
switch {
case start == end:
pos = end + 1
case end > pos:
pos = end
default:
pos++
}
if pos > len(src) {
break
}
}
if !matched {
return src
}
buf.WriteString(src[lastEnd:])
return buf.String()
}
// Expand appends template to dst and returns the result; during the
// append, Expand replaces variables in the template with corresponding
// matches drawn from src. The match slice should contain the progressively
// numbered submatches as returned by FindSubmatchIndex.
//
// In the template, a variable is denoted by a substring of the form $name
// or ${name}, where name is a non-empty sequence of letters, digits, and
// underscores. A purely numeric name like $1 refers to the submatch with
// the corresponding index; other names refer to capturing parentheses
// named with the (?P<name>...) syntax. A reference to an out of range or
// unmatched index or a name that is not present in the regular expression
// is replaced with an empty slice.
//
// In the $name form, name is taken to be as long as possible: $1x is
// equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.
//
// To insert a literal $ in the output, use $$ in the template.
func (r *Regex) Expand(dst []byte, template []byte, src []byte, match []int) []byte {
return r.expand(dst, template, src, match)
}
// ExpandString is like Expand but the template and source are strings.
// It appends to and returns a byte slice in order to give the caller
// control over allocation.
func (r *Regex) ExpandString(dst []byte, template string, src string, match []int) []byte {
return r.expand(dst, []byte(template), []byte(src), match)
}
// expand appends template to dst and returns the result; during the
// append, it replaces $1, $2, etc. with the corresponding submatch.
// $0 is the entire match.
func (r *Regex) expand(dst []byte, template []byte, src []byte, match []int) []byte {
i := 0
for i < len(template) {
if template[i] != '$' || i+1 >= len(template) {
dst = append(dst, template[i])
i++
continue
}
// Handle $ escape sequences
next := template[i+1]
// Check for $0-$9
if next >= '0' && next <= '9' {
groupNum := int(next - '0')
// Each group occupies 2 indices in match array
groupIdx := groupNum * 2
if groupIdx+1 < len(match) && match[groupIdx] >= 0 {
dst = append(dst, src[match[groupIdx]:match[groupIdx+1]]...)
}
i += 2
continue
}
// Check for ${name} - not supported yet, treat as literal
if next == '{' {
dst = append(dst, '$')
i++
continue
}
// $$ -> $
if next == '$' {
dst = append(dst, '$')
i += 2
continue
}
// Unknown $ escape, treat as literal
dst = append(dst, '$')
i++
}
return dst
}
// ReplaceAll returns a copy of src, replacing matches of the pattern
// with the replacement bytes repl.
// Inside repl, $ signs are interpreted as in Regexp.Expand:
// $0 is the entire match, $1 is the first capture group, etc.
//