MCPcopy Create free account
hub / github.com/coregx/coregex / Split

Method Split

regex.go:1288–1337  ·  view source on GitHub ↗

Split slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches. The slice returned by this method consists of all the substrings of s not contained in the slice returned by FindAllString. When called on an expression that contains n

(s string, n int)

Source from the content-addressed store, hash-verified

1286// parts = re.Split("a,b,c", 2)
1287// // parts = ["a", "b,c"]
1288func (r *Regex) Split(s string, n int) []string {
1289 if n == 0 {
1290 return nil
1291 }
1292
1293 indices := r.FindAllStringIndex(s, -1)
1294 if len(indices) == 0 {
1295 // No matches, return entire string
1296 return []string{s}
1297 }
1298
1299 // Determine the number of splits
1300 numSplits := len(indices) + 1
1301 if n > 0 && n < numSplits {
1302 numSplits = n
1303 }
1304
1305 // Pre-allocate result slice
1306 result := make([]string, 0, numSplits)
1307
1308 lastEnd := 0
1309 for _, idx := range indices {
1310 // Skip empty match at the beginning (position 0 with zero-width match)
1311 // This matches stdlib behavior: Split("", "abc") = ["a", "b", "c"], not ["", "a", "b", "c", ""]
1312 if lastEnd == 0 && idx[0] == 0 && idx[1] == 0 {
1313 continue
1314 }
1315
1316 // Skip empty match at the very end of string
1317 if idx[0] == len(s) && idx[1] == len(s) {
1318 break
1319 }
1320
1321 // Add substring before match
1322 result = append(result, s[lastEnd:idx[0]])
1323 lastEnd = idx[1]
1324
1325 // Check if we've reached the limit (but need room for final element)
1326 if n > 0 && len(result) >= n-1 {
1327 // Add the rest as the final element
1328 result = append(result, s[lastEnd:])
1329 return result
1330 }
1331 }
1332
1333 // Add remaining text after last match
1334 // Always add even if empty (matches stdlib behavior)
1335 result = append(result, s[lastEnd:])
1336 return result
1337}
1338
1339// Count returns the number of non-overlapping matches of the pattern in b.
1340// If n > 0, counts at most n matches. If n <= 0, counts all matches.

Callers 9

TestStdlibCompat_SplitFunction · 0.45
FuzzSplitStdlibFunction · 0.45
TestSplitFunction · 0.45
TestGoAWK_SplitPatternFunction · 0.45
BenchmarkGoAWK_SplitFunction · 0.45
BenchmarkSplitFunction · 0.45
epsilonClosureIntoMethod · 0.45
resolveWordBoundariesMethod · 0.45
epsilonClosureOnePassMethod · 0.45

Calls 1

FindAllStringIndexMethod · 0.95

Tested by 6

TestStdlibCompat_SplitFunction · 0.36
FuzzSplitStdlibFunction · 0.36
TestSplitFunction · 0.36
TestGoAWK_SplitPatternFunction · 0.36
BenchmarkGoAWK_SplitFunction · 0.36
BenchmarkSplitFunction · 0.36