How to split a string on multiple single‑character delimiters (and keep them) in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "regexp"
)

func SplitKeepDelims(s string, delimiters string) []string {
    // Build regex: e.g. ",;|" → "([,;|])"
    pattern := "([" + regexp.QuoteMeta(delimiters) + "])"
    re := regexp.MustCompile(pattern)

    result := []string{}
    lastEnd := 0

    // Find all delimiter matches
    matches := re.FindAllStringIndex(s, -1)

    for _, m := range matches {
        start, end := m[0], m[1]

        // Add text before delimiter
        if start > lastEnd {
            result = append(result, s[lastEnd:start])
        }

        // Add the delimiter itself
        result = append(result, s[start:end])

        lastEnd = end
    }

    // Add remaining text after last delimiter
    if lastEnd < len(s) {
        result = append(result, s[lastEnd:])
    }

    return result
}

func main() {
    input := "aa,bbb;cccc|ddddd"
    parts := SplitKeepDelims(input, ",;|")

    for _, p := range parts {
        fmt.Printf("[%s] ", p)
    }
}



/*
run:

[aa] [,] [bbb] [;] [cccc] [|] [ddddd] 

*/

 



answered Mar 9 by avibootz

Related questions

...