-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstrings.go
1401 lines (1337 loc) · 37.1 KB
/
strings.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
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
// -----------------------------------------------------------------------------
// ZR Library zr/[strings.go]
// (c) balarabe@protonmail.com License: MIT
// -----------------------------------------------------------------------------
package zr
// # String Functions
// After(s string, find ...string) string
// CamelCase(s string) string
// CompactSpaces(s string) string
// ContainsI(s, substr string) bool
// ContainsWord(s, word string, caseMode CaseMode) bool
// CountCRLF(s string) (count, countCR, countLF int)
// EqualStringSlices(a, b []string) bool
// FindChar(s string, ch byte, beginIndex int) int
// FindInSlice(s string, start, end int, substr string) int
// First(s string, count int) string
// GetPart(s, prefix, suffix string) string
// IfString(condition bool, trueStr, falseStr string) string
// IndexOfString(s string, ar []string) int
// IsIdentifier(s string) bool
// IsWhiteSpace(s string) bool
// JSUnescapeStruct(structPtr interface{})
// JSUnescape(s string) string
// Last(s string, count int) string
// LineBeginIndex(s string, index int) int
// LineBeginIndexB(s []byte, index int) int
// LineEndIndex(s string, index int) int
// LineEndIndexB(s []byte, index int) int
// LineOfIndex(s string, index int) string
// LineOffsetUTF8(data []byte, lineIndex int) (byteOffset, charOffset int)
// Padf(minLength int, format string, args ...interface{}) string
// ReplaceEx1(s, find, repl string, count int, caseMode CaseMode) string
// ReplaceI(s, find, repl string, optCount ...int) string
// ReplaceMany(
// s string,
// finds []string,
// repls []string,
// count int,
// caseMode CaseMode,
// wordMode WordMode,
// ) string
// ReplaceWord(s, find, repl string, caseMode CaseMode) string
// SetPart(s, prefix, suffix, part string) string
// SetSlice(s string, start, end int, substr string) string
// ShowSpaces(s string) string
// SkipChars(s string, start int, chars string) int
// SkipName(s string, start int) int
// SkipSpaces(s string, start int) int
// Slice(s string, beginIndex, endIndex int) string
// SplitQuoted(s string) []string
// StrOneOf(s string, matches ...string) bool
// String(value interface{}) string
// StringE(value interface{}) (string, error)
// Substr(s string, charIndex, charCount int) string
// // TODO: ^beginIndex, endIndex. Why Substr when there's Slice()?
// TitleCase(s string) string
// TokenGet(list string, index int, sep string) string
// TokenGetEx(list string, index int, sep string, ignoreEnd bool) string
// WordIndex(s, word string, caseMode CaseMode) int
import (
"bytes"
"errors"
"fmt"
"reflect"
"sort"
"strconv"
"strings"
"unicode"
"unicode/utf8"
)
// CaseMode type specifies if text comparisons are case sensitive.
// Various functions have a CaseMode parameter.
//
// There are two possible values:
//
// IgnoreCase: text is matched irrespective of letter capitalization.
// MatchCase: case must be matched exactly.
type CaseMode uint
// IgnoreCase constant specifies that text
// comparisons should not be case sensitive.
const IgnoreCase = CaseMode(1)
// MatchCase constant specifies that text
// comparisons should be case sensitive.
const MatchCase = CaseMode(2)
// WordMode type determines if a search should match whole
// words when searching (or replacing, etc.) a string.
//
// Words are composed of alphabetic and numeric
// characters and underscores.
//
// There are two possible values:
// IgnoreWord: do not match distinct words.
// MatchWord: match distinct words.
type WordMode uint
// IgnoreWord constant specifies that string
// searches should not match distinct words.
const IgnoreWord = WordMode(1)
// MatchWord constant specifies that string
// searches should match distinct words.
const MatchWord = WordMode(2)
// -----------------------------------------------------------------------------
// # String Functions
// After returns the part of 's' immediately after the last 'find' string.
func After(s string, find ...string) string {
if s == "" {
return ""
}
at := -1
for _, f := range find {
i := strings.Index(s, f)
if i != -1 {
i += len(f)
if i > at {
at = i
}
}
}
if at == -1 {
return ""
}
return s[at:]
} // After
// CamelCase converts an identifier from underscore naming convention
// to camel case naming convention: 'some_name' becomes 'someName'.
func CamelCase(s string) string {
var (
retBuf = bytes.NewBuffer(make([]byte, 0, len(s)))
ws = retBuf.WriteString
ucase bool
)
for _, ch := range s {
if ch == '_' {
ucase = true
continue
}
if ucase {
ucase = false
ch = unicode.ToUpper(ch)
}
ws(string(ch))
}
return retBuf.String()
} // CamelCase
// CompactSpaces reduces all multiple white-spaces in string to
// a single space, also converting newlines and tabs to space.
// E.g. "a\n b c" becomes "a b c".
func CompactSpaces(s string) string {
for _, ch := range "\a\b\f\n\r\t\v" { // <- no need to include a space here
if strings.Contains(s, string(ch)) {
s = strings.ReplaceAll(s, string(ch), " ")
}
}
for strings.Contains(s, " ") {
s = strings.ReplaceAll(s, " ", " ")
}
return s
} // CompactSpaces
// ContainsI returns true if 's' contains 'substr', ignoring case.
// It always returns true if 'substr' is a blank string.
func ContainsI(s, substr string) bool {
s, substr = strings.ToLower(s), strings.ToLower(substr)
return strings.Contains(s, substr)
} // ContainsI
// ContainsWord returns true if 's' contains 'word', provided 'word'
// is a distinct word in 's', that is, the characters before
// and after 'word' are not alphanumeric or underscores.
// It always returns true if 'word' is a blank string.
// Specify MatchCase or IgnoreCase to determine
// if the case should me matched or ignored.
func ContainsWord(s, word string, caseMode CaseMode) bool {
return WordIndex(s, word, caseMode) != -1
} // ContainsWord
// CountCRLF returns the number of carriage returns and line feeds in
// the given string in 3 components: CR+LF count, CR count, LF count.
func CountCRLF(s string) (count, countCR, countLF int) {
for _, ch := range s {
if ch == '\r' {
countCR++
} else if ch == '\n' {
countLF++
}
}
return countCR + countLF, countCR, countLF
} // CountCRLF
// EqualStringSlices reports whether two
// string slices a and b are identical.
func EqualStringSlices(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i, l := 0, len(a); i < l; i++ {
if a[i] != b[i] {
return false
}
}
return true
} // EqualStringSlices
// FindChar _ _
func FindChar(s string, ch byte, beginIndex int) int {
return beginIndex + strings.IndexByte(s[beginIndex:], ch)
} // FindChar
// FindInSlice _ _
func FindInSlice(s string, start, end int, substr string) int {
if start == 0 && end == -1 {
return strings.Index(s, substr)
}
sLen := len(s)
if start < 0 || start > sLen {
mod.Error(EInvalidArg, "start index:", start)
if start < 0 {
start = 0
} else {
return -1
}
}
if end == -1 || end > sLen {
end = sLen
}
if start > end {
mod.Error("Start index", start, "> end index", end)
return -1
}
return start + strings.Index(s[start:end], substr)
} // FindInSlice
// First _ _
func First(s string, count int) string {
if count < 0 {
mod.Error("Negative count:", count)
return ""
}
sLen := len(s)
if count > sLen {
mod.Error(EInvalidArg, "count", count, "out of range", sLen)
count = sLen
}
return s[:count]
} // First
// GetPart returns the substring between 'prefix' and 'suffix'.
// When the prefix is blank, returns the part from the beginning of 's'.
// When the suffix is blank, returns the part up to the end of 's'.
// I.e. if prefix and suffix are both blank, returns 's'.
// When either prefix or suffix is not found, returns a zero-length string.
func GetPart(s, prefix, suffix string) string {
at := strings.Index(s, prefix)
if at == -1 {
return ""
}
s = s[at+len(prefix):]
if suffix == "" {
return s
}
at = strings.Index(s, suffix)
if at == -1 {
return ""
}
return s[:at]
} // GetPart
// IfString is a conditional IF expression: If 'condition' is true,
// returns string 'trueStr', otherwise returns string 'falseStr'.
// Not to be confused with IfStr() function, which uses Str objects.
func IfString(condition bool, trueStr, falseStr string) string {
if condition {
return trueStr
}
return falseStr
} // IfString
// IndexOfString returns the index of string [s] in string slice [ar].
func IndexOfString(s string, ar []string) int {
for i, it := range ar {
if it == s {
return i
}
}
return -1
} // IndexOfString
// IsIdentifier checks if 's' contains only letters, numbers or underscores.
func IsIdentifier(s string) bool {
if s == "" {
return false
}
for _, ch := range s {
if ch != '_' && !unicode.IsLetter(ch) && !unicode.IsDigit(ch) {
return false
}
}
return true
} // IsIdentifier
// IsWhiteSpace returns true if all the
// characters in a string are white-spaces.
func IsWhiteSpace(s string) bool {
if s == "" {
return false
}
for _, ch := range s {
if ch != ' ' && ch != '\a' &&
ch != '\b' && ch != '\f' &&
ch != '\n' && ch != '\r' &&
ch != '\t' && ch != '\v' {
return false
}
}
return true
} // IsWhiteSpace
// JSUnescape unescapes a string escaped with the JavaScript
// escape() function (which is deprecated).
// In such escaped strings:
// % is followed by a 2-digit hex value.
// e.g. escaped string "%25" becomes "%", "%20" becomes " ", etc.
func JSUnescape(s string) string {
var (
retBuf = bytes.NewBuffer(make([]byte, 0, len(s)))
wr = retBuf.WriteRune
hexPower = 0
hexVal = rune(0)
)
for _, ch := range s {
if ch == '%' {
hexPower = 2
hexVal = 0
} else if hexPower != 0 {
var digit rune
if ch >= '0' && ch <= '9' {
digit = ch - '0'
} else if ch >= 'a' && ch <= 'f' {
digit = ch - 'a' + 10
} else if ch >= 'A' && ch <= 'F' {
digit = ch - 'A' + 10
}
if hexPower == 2 {
digit *= 16
}
hexVal += digit
if hexPower == 1 {
wr(hexVal)
}
hexPower--
} else {
wr(ch)
}
}
return retBuf.String()
} // JSUnescape
// JSUnescapeStruct unescapes all the strings in a struct that have been
// escaped with the JavaScript escape() function (which is deprecated).
// In such escaped strings: % is followed by a 2-digit
// hex value. e.g. escaped string "%25" becomes "%", "%20" becomes " ", etc.
func JSUnescapeStruct(structPtr interface{}) {
structT := reflect.TypeOf(structPtr)
if structT.Kind() != reflect.Ptr {
mod.Error(EInvalidArg, "^structPtr", "is not a pointer;",
"it is^", structT.Kind())
return
}
if structT.Elem().Kind() != reflect.Struct {
mod.Error(EInvalidArg, "^structPtr", "is not a pointer to a struct;",
"it is^", structT.Elem().Kind())
return
}
structT = structT.Elem()
structV := reflect.ValueOf(structPtr).Elem()
for i := 0; i < structT.NumField(); i++ {
fieldV := structV.Field(i)
fieldK := fieldV.Kind()
if fieldK == reflect.String {
fieldV.SetString(JSUnescape(strings.TrimSpace(fieldV.String())))
} else if fieldK == reflect.Slice {
for rowNo := 0; rowNo < fieldV.Len(); rowNo++ {
JSUnescapeStruct(fieldV.Index(rowNo).Addr().Interface())
}
}
}
} // JSUnescapeStruct
// Last _ _
func Last(s string, count int) string {
if count < 0 {
mod.Error("Negative count:", count)
return ""
}
sLen := len(s)
if count > sLen {
mod.Error(EInvalidArg, "count", count, "out of range", sLen)
count = sLen
}
return s[sLen-count : sLen]
} // Last
// LineBeginIndex _ _
func LineBeginIndex(s string, index int) int {
sLen := len(s)
if index == -1 {
index = sLen
}
if index < -1 || index > sLen {
mod.Error("Index", index, "out of range -1 to", sLen)
if index < -1 {
index = 0
} else if index > sLen {
index = sLen
}
}
cr := strings.LastIndexByte(s[:index], '\r')
lf := strings.LastIndexByte(s[:index], '\n')
if cr > lf {
return cr + 1
}
return lf + 1
} // LineBeginIndex
// LineBeginIndexB _ _
func LineBeginIndexB(s []byte, index int) int {
sLen := len(s)
if index == -1 {
index = sLen
}
if index < -1 || index > sLen {
mod.Error("Index", index, "out of range -1 to ", sLen)
if index < -1 {
index = 0
} else if index > sLen {
index = sLen
}
}
cr := bytes.LastIndexByte(s[:index], '\r')
lf := bytes.LastIndexByte(s[:index], '\n')
if cr > lf {
return cr + 1
}
return lf + 1
} // LineBeginIndexB
// LineEndIndex _ _
func LineEndIndex(s string, index int) int {
sLen := len(s)
if index == -1 {
return sLen
} else if index < -1 || index > sLen {
mod.Error("Index", index, "out of range -1 to", sLen)
if index < -1 {
index = 0
} else if index > sLen {
index = sLen
}
}
cr := strings.IndexByte(s[index:], '\r')
lf := strings.IndexByte(s[index:], '\n')
var i int
if (cr < lf && cr != -1) || lf == -1 {
i = cr
} else {
i = lf
}
if i == -1 {
return sLen
}
return index + i
} // LineEndIndex
// LineEndIndexB _ _
func LineEndIndexB(s []byte, index int) int {
sLen := len(s)
if index == -1 {
index = 0
} else if index < -1 || index > sLen {
mod.Error("Index", index, "out of range -1 to", sLen)
if index < -1 {
index = 0
} else if index > sLen {
index = sLen
}
}
var (
cr = bytes.IndexByte(s[index:], '\r')
lf = bytes.IndexByte(s[index:], '\n')
i = lf
)
if cr != -1 && cr < lf {
i = cr
}
if i == -1 {
return sLen
}
return index + i
} // LineEndIndexB
// LineOfIndex _ _
func LineOfIndex(s string, index int) string {
if index < 0 || index > len(s) {
return ""
}
begin := LineBeginIndex(s, index)
end := LineEndIndex(s, index)
return s[begin:end]
} // LineOfIndex
// LineOffsetUTF8 returns the byte and character offsets of
// the beginning of a line specified by 'lineIndex', within
// a UTF8-encoded slice of bytes ('data').
func LineOffsetUTF8(data []byte, lineIndex int) (byteOffset, charOffset int) {
if lineIndex < 0 {
mod.Error(EInvalidArg, "^lineIndex", ":", lineIndex)
return -1, -1
}
if lineIndex == 0 {
return 0, 0
}
end := len(data) - 1
cc := 0 // number of utf8 continuation characters
for i, b := range data {
byteOffset++
if cc > 0 {
if (b & 0xC0) != 0x80 { // (b & 11 000000) == 10 000000
Error(fmt.Sprintf(
"Bad UTF8 continuation: %dd 0x%2Xh %8bb", b, b, b,
))
}
cc--
continue
}
// From RFC 2044:
//
// UCS-4 range (hex.) UTF-8 octet sequence (binary)
// 0000 0000-0000 007F 0xxxxxxx
// 0000 0080-0000 07FF 110xxxxx 10xxxxxx
// 0000 0800-0000 FFFF 1110xxxx 10xxxxxx 10xxxxxx
//
// 0001 0000-001F FFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
// 0020 0000-03FF FFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
//
// 0400 0000-7FFF FFFF 1111110x 10xxxxxx ... 10xxxxxx
switch {
case b < 128:
{
charOffset++
}
case (b & 0xE0) == 0xC0: // (b & 111 00000) == 110 00000
{
charOffset++
cc = 2 - 1
continue
}
case (b & 0xF0) == 0xE0: // (b & 1111 0000) == 1110 0000
{
charOffset++
cc = 3 - 1
continue
}
case (b & 0xF8) == 0xF0: // (b & 11111 000) == 11110 000
{
charOffset++
cc = 4 - 1
continue
}
case (b & 0xFC) == 0xF8: // (b & 111111 00) == 111110 00
{
charOffset++
cc = 5 - 1
continue
}
default:
Error(fmt.Sprintf(
"UTF8 lead byte not handled: %dd 0x%2Xh %8bb", b, b, b,
))
}
if b == '\n' || (b == '\r' && (i == end || data[i+1] != '\n')) {
// ^handle the strange case of \r-delimited lines^
lineIndex--
if lineIndex <= 0 {
return byteOffset, charOffset
}
}
}
return -1, -1
} // LineOffsetUTF8
// Padf suffixes a string with spaces to make sure it is at least
// 'minLength' characters wide. I.e. the string is left-aligned.
// If the string is wider than 'minLength', returns the string as it is.
func Padf(minLength int, format string, args ...interface{}) string {
format = fmt.Sprintf(format, args...)
if len(format) < minLength {
return format + strings.Repeat(" ", minLength-len(format))
}
return format
} // Padf
// ReplaceEx1 _ _
// Specify MatchCase or IgnoreCase for case mode.
func ReplaceEx1(s, find, repl string, count int, caseMode CaseMode) string {
if find == repl || count == 0 {
return s // avoid allocation
}
var (
sLen = len(s)
findLen = len(find)
//
// pre-allocate a buffer (assume each char uses 2 bytes on average)
retBuf = bytes.NewBuffer(make([]byte, 0,
2*int(float64(sLen)/float64(findLen)*float64(len(repl)+1))))
ws = retBuf.WriteString
)
// lowercase of 's' and 'find' used when caseMode is IgnoreCase
var sLw, findLw string
if caseMode == IgnoreCase {
sLw = strings.ToLower(s)
findLw = strings.ToLower(find)
}
var (
replRemain = count // number of replacements remaining
pos, prev = 0, 0
)
for pos < sLen {
// find the next index of 'find' in 's'
var i int
if caseMode == IgnoreCase {
i = strings.Index(sLw[pos:], findLw)
} else {
i = strings.Index(s[pos:], find)
}
// no more matches? append the rest
if i == -1 || replRemain == 0 {
ws(s[prev:])
break
}
pos += i // add i to pos because i is relative to slice
// text between matches
if pos > 0 {
ws(s[prev:pos])
}
ws(repl)
replRemain--
prev = pos + findLen
pos += findLen
}
return retBuf.String()
// TODO: Use an array instead of bytes.Buffer. See Replace() in library.
} // ReplaceEx1
// ReplaceI replaces 'find' with 'repl' ignoring case.
func ReplaceI(s, find, repl string, optCount ...int) string {
count := -1
switch n := len(optCount); {
case n == 1:
{
count = optCount[0]
}
case n > 1:
{
mod.Error(EInvalidArg, "optCount", ":", optCount)
}
}
return ReplaceEx1(s, find, repl, count, IgnoreCase)
} // ReplaceI
// ReplaceMany makes multiple string replacements in a single pass.
// Replacing is prioritized, with longest strings among 'finds'
// replaced first before shorter strings.
//
// With this function you can exchange or transpose values, which simple
// replace() functions can not do without making temporary replacements.
//
// It is much faster to call ReplaceMany() with a batch of different
// replacements (even thousands of items), than to call a simple replace()
// function repeatedly. However if you only need to replace one string,
// then standard strings.Replace() or zr.ReplaceWord() and similar
// functions run faster when making an isolated replacement.
//
// Internally, ReplaceMany() works with Unicode characters, therefore
// 's', 'finds' and 'repls' can be ANSI or UTF-8 encoded strings.
//
// Parameters:
//
// s: the string being replaced.
//
// finds: a list of strings to find. each item will be replaced
// with the matching item in repls, so the length of
// 'finds' and 'repls' must be the same.
//
// repls: a list of replacement strings.
//
// count: maximum number of replacements to make, or -1 for unlimited.
//
// caseMode: use MatchCase for case-sensitive search string matching
// or IgnoreCase for case-insensitive search string matching.
//
// wordMode: use MatchWord to match whole words only, or IgnoreWord to
// replace everything. Distinct words are comprised of letters,
// numbers and underscores.
func ReplaceMany(
s string,
finds []string,
repls []string,
count int,
caseMode CaseMode,
wordMode WordMode,
) string {
// Note: this large function is split into sub-functions.
// Processing begins after everything is declared. See run().
if count == 0 || len(finds) == 0 {
return s // avoid allocation
}
// batch _ _
type batch struct {
findLen int
finds []string
repls []string
}
// tree _ _
type tree struct {
find string // what to find
repl string // what to replace with
done int // number of replacements made so far
sub map[rune]*tree // a 'branch' of the tree
}
// getBatches _ _
getBatches := func(finds, repls []string) ([]int, map[int]*batch) {
var lengths []int
batches := map[int]*batch{}
for i, find := range finds {
n := utf8.RuneCountInString(find)
_, has := batches[n]
if !has {
batches[n] = &batch{findLen: n}
lengths = append(lengths, n)
}
b := batches[n]
if find == repls[i] {
continue
}
b.finds = append(b.finds, find)
b.repls = append(b.repls, repls[i])
}
sort.Sort(sort.Reverse(sort.IntSlice(lengths)))
return lengths, batches
}
// getTree _ _
getTree := func(finds, repls []string, caseMode CaseMode) (ret tree) {
ret.sub = make(map[rune]*tree)
for f, find := range finds {
i := 0
node := &ret
last := utf8.RuneCountInString(find)
for _, ch := range find {
i++ // ^ don't use the index in for, that's a byte index
if caseMode == IgnoreCase {
ch = unicode.ToLower(ch)
}
_, exist := node.sub[ch]
var sub *tree
if exist {
sub = node.sub[ch]
} else {
sub = &tree{sub: make(map[rune]*tree)}
}
if i == last {
sub.find = find
sub.repl = repls[f]
}
node.sub[ch] = sub
node = sub
}
}
return ret
}
// replaceMany _ _
replaceMany := func(
s string,
finds []string,
repls []string,
count int,
caseMode CaseMode,
wordMode WordMode,
) string {
var (
src = []rune(s)
srcLen = len(src)
root = getTree(finds, repls, caseMode)
node = &root // *tree pointing to current branch
match = 0 // <- number of matching characters
prev = 0
retBuf = bytes.NewBuffer(make([]byte, 0, int(1.5*float64(len(s)))))
ws = retBuf.WriteString
)
for i := 0; i < srcLen; i++ {
ch := src[i]
if caseMode == IgnoreCase {
ch = unicode.ToLower(ch)
}
// check if the character is found under the current branch
// if not, reset matching count and start over from root
{
sub, found := node.sub[ch]
if !found {
node = &root
i -= match
match = 0
continue
}
match++
node = sub
}
findLen := utf8.RuneCountInString(node.find)
if findLen == 0 || findLen != match {
continue
}
if wordMode == MatchWord {
var l, r rune
if (i - findLen + 1) > 0 {
l = src[i-findLen]
}
if i < (srcLen - 1) {
r = src[i+1]
}
if l == '_' || unicode.IsDigit(l) || unicode.IsLetter(l) ||
r == '_' || unicode.IsDigit(r) || unicode.IsLetter(r) {
continue
}
}
if count >= 0 && node.done >= count {
break
}
node.done++
if prev < i-findLen+1 {
ws(string(src[prev : i-findLen+1]))
}
ws(node.repl)
prev = i + 1
node = &root
match = 0
}
// write the 'tail' of the string
if prev < srcLen {
ws(string(src[prev:]))
}
return retBuf.String()
// TODO: Use an array instead of bytes.Buffer. See Replace() in library.
}
run := func() string {
// validate arguments
const erv = ""
if len(finds) != len(repls) {
mod.Error(EInvalidArg, ": lengths don't match:",
len(finds), "and", len(repls))
return erv
}
if caseMode != IgnoreCase && caseMode != MatchCase {
mod.Error(EInvalidArg,
"^caseMode", ":", caseMode, "defaulting to 'MatchCase'")
caseMode = MatchCase
}
if wordMode != IgnoreWord && wordMode != MatchWord {
mod.Error(EInvalidArg,
"^wordMode", ":", wordMode, "defaulting to 'IgnoreWord'")
wordMode = IgnoreWord
}
lengths, batches := getBatches(finds, repls)
for _, n := range lengths {
b, _ := batches[n]
s = replaceMany(s, b.finds, b.repls, count, caseMode, wordMode)
}
return s
}
return run()
} // ReplaceMany
// ReplaceWord replaces a word in a string. _ _
// Specify MatchCase or IgnoreCase for case mode.
//
// Examples:
// ReplaceWord("ab b c", "b", "z", MatchCase) // returns "ab z c"
// ReplaceWord("ab b c", "B", "Z", IgnoreCase) // returns "ab Z c"
func ReplaceWord(s, find, repl string, caseMode CaseMode) string {
if find == repl {
return s // avoid allocation
}
var (
sLen = len(s)
findLen = len(find)
pos = 0
prev = 0
ret = ""
sLw = "" // lowercase of 's' and 'find' when caseMode is IgnoreCase
findLw = ""
)
if caseMode == IgnoreCase {
sLw = strings.ToLower(s)
findLw = strings.ToLower(find)
}
nonWord := func(ch byte) bool {
// TODO: wrongly returns 'false' for non-Latin Unicode letters
return !((ch >= '0' && ch <= '9') || ch == '_' ||
(ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
}
for {
{ // find the next index of 'find' in 's'
var i int
if caseMode == IgnoreCase {
i = strings.Index(sLw[pos:], findLw)
} else {
i = strings.Index(s[pos:], find)
}
if i == -1 {
ret += s[prev:] // no more matches? append the rest
break
}
pos += i
}
ret += s[prev:pos] // text between words
// left word boundary:
c := byte(0)
if pos > 0 {
c = s[pos-1]
}
onLeft := nonWord(c)
// right word boundary:
c = 0
if pos+findLen < sLen {
c = s[pos+findLen]
}
onRight := nonWord(c)
// an isolated word?
if onLeft && onRight {
ret += repl // append replacement
} else {
ret += find
}
prev = pos + findLen
pos += findLen
}
return ret
} // ReplaceWord
// SetPart __ // TODO: describe and create unit test
func SetPart(s, prefix, suffix, part string) string {
at := strings.Index(s, prefix)
if at == -1 {
return s + prefix + part + suffix
}
head := s[:at+len(prefix)]
tail := s[at+len(prefix):]
at = strings.Index(tail, suffix)
if at == -1 {
tail = suffix
} else {
tail = tail[at:]
}
return head + part + tail
} // SetPart
// SetSlice _ _
func SetSlice(s string, start, end int, substr string) string {
if start == 0 && end == -1 {
return substr
}
sLen := len(s)
if start < 0 || start > sLen {
mod.Error(EInvalidArg, "start index:", start)
if start < 0 {
start = 0
} else {
return s
}
}
if end == -1 || end > sLen {
end = sLen
}