I'm splitting strings from this format:
"I[07-06|19:56:12.407] Added to precommit module=consensus vote="Vote{2:8FD0F8F1E2FA 1/00/2(Precommit) D7D7C52037F0 /E305561D4A6C.../}" precommits="VoteSet{H:1 R:0 T:2 +2/3:<nil> BA{4:__X_} map[]}"
Like this:
descripParse := strings.Split(string, "module")
When I use a string like the one above:
descripParse[1] == "=consensus vote="Vote{2:8FD0F8F1E2FA 1/00/2(Precommit) D7D7C52037F0 /E305561D4A6C.../}" precommits="VoteSet{H:1 R:0 T:2 +2/3:<nil> BA{4:__X_} map"
You'll notice that everything after and including [] is gone. This is bad, but what's much worse is when the [] occurs in the line prior to "module", like this:
"I[07-06|19:56:12.637] Added to lastPrecommits: VoteSet{H:2 R:0 T:2 +2/3:DAF77215090623803CB9715FFD98F58E24A37252:1:C10362D25921 BA{4:XXXX} map[]} module=consensus"
Here, if I query for descripParse[1]
, my program panics:
panic: runtime error: index out of range
because the split point occurs after the [], and:
descripParse[0] == "I[07-06|19:56:12.637] Added to lastPrecommits: VoteSet{H:2 R:0 T:2 +2/3:DAF77215090623803CB9715FFD98F58E24A37252:1:C10362D25921 BA{4:XXXX} map"
What's happening?
Because there are special characters within the string you must use the backtick (`) character to define the string not the double quote ("
) character
For more on this topic checkout string literals in the language specifications https://golang.org/ref/spec#String_literals
Here is a little piece of demo code which works: https://play.golang.org/p/Bf70i5u3MO
package main
import (
"fmt"
"strings"
)
func main() {
str := `I[07-06|19:56:12.407] Added to precommit module=consensus vote="Vote{2:8FD0F8F1E2FA 1/00/2(Precommit) D7D7C52037F0 /E305561D4A6C.../}" precommits="VoteSet{H:1 R:0 T:2 +2/3:<nil> BA{4:__X_} map[]}`
fmt.Println(str)
descripParse := strings.Split(str, "module")
fmt.Println(len(descripParse))
fmt.Println(descripParse)
if descripParse[1] == `=consensus vote="Vote{2:8FD0F8F1E2FA 1/00/2(Precommit) D7D7C52037F0 /E305561D4A6C.../}" precommits="VoteSet{H:1 R:0 T:2 +2/3:<nil> BA{4:__X_} map[]}` {
fmt.Println("WOOHOO!")
} else {
fmt.Println(descripParse[1])
}
}