arraysstringgoterratest

Converting a string to array


I am working with Go for writing a terratest and I have string "[[IFN_EYE_HUBW_DEV_AUTO_01] [IFN_EW_HUBW_DEV_AUTO_02]]". How can I split this to an array to get "IFN_EYE_HUBW_DEV_AUTO_01" and "IFN_EW_HUBW_DEV_AUTO_02" as 1st and 2nd element of the array in go?


Solution

  • You can simply replace all [ and ] and then split them with Fields as:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        inp := "[[IFN_EYE_HUBW_DEV_AUTO_01] [IFN_EW_HUBW_DEV_AUTO_02]]"
        inp = strings.ReplaceAll(inp, "[", "")
        inp = strings.ReplaceAll(inp, "]", "")
        out := strings.Fields(inp)
        fmt.Printf("%v, %v", out[0], out[1])
    }
    

    Ideally, you should use regex for pattern matching but the above will work just fine for this task.

    Go demo here

    Note: It will replace all the [ and ] brackets so if a string has these brackets then will be replaced too.