regex.Split but keep separator

Hello,
I’m splitting txt parts by regex, the issue is thag reg.Split removes the separator.
Is there better way (more efficient) to keep it than this?

reg := regexp.MustCompile(`(?m)^\[\d+:\d+:\d+]`)

split := reg.Split(string(log), -1)

var test []string

for index, line := range split {
    submatch := reg.FindAllStringSubmatch(string(log), -1)
    submatch2 := submatch[index][0]

    test = append(test, submatch2 + line)
}

Because if I’m not wrong, it do “regexing” 2 times which is bad because I need it to be fast as possible

@abcdef Can you provide some example input text and desired output text?

1 Like

Here is the code example: Go Playground - The Go Programming Language

Desired output is “[HH:mm:ss] something[num]” instead of just “something[num]”

You’re getting just “something[num]” because you’re using (*Regexp).Split which finds the pattern you specify and splits a string every time it finds that text, just like strings.Split. You say you want “[HH:mm:ss] something[num]”, but the source text is already formatted that way, so why are you parsing it just to put it back into that format?

@abcdef - So you have input that comes in linewise –

[01:00:00] something1
[02:00:00] something2
[03:00:00] something3
[04:00:00] something4

– and want to put each line into a slice field?

If you include the rest of the line in the regex (.*$) and use FindAllString instead of Split (Playground, you get a slice of [HH:mm:ss] something[num] values back.

[[01:00:00] something1 [02:00:00] something2 [03:00:00] something3 [04:00:00] something4]

Is this the output you are looking for?

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.