Reputation: 6522
I have strings of the format %s/%s/%s:%s
where there are four substrings. The first three substrings are separated by a /
and the last one by a :
. I want to extract the individual sub-strings. For example:
package main
import (
"regexp"
"fmt"
)
func main() {
re := regexp.MustCompile(".*/.*/.*:.*")
fmt.Println(re.FindAllStringSubmatch("a/b/c-c:d", -1))
}
In the above program I wanted: a
, b
, c-c
and d
to be printed as individual elements. But I am not able to extract the individual fields. The entire string is returned as the first element of the array that FindAllStringSubmatch
returns. What is the way to extract the individual elements that match the regex ?
Playground link: https://play.golang.org/p/M1sKGl0n2tK
Upvotes: 0
Views: 936
Reputation: 5166
Use split as it's pattern is fixed you know it's :
separated then /
separated regex is expensive CPU process
parts := strings.Split("a/b/c-c:d", ":")
fmt.Println(strings.Split(parts[0], "/"), parts[1])
& if you prefer using regex then also use full match ^
at the beginning & $
at the end
"^([^/]+)/([^/]+)/([^/]+):([^:]+)$"
e.g this will not match "a/a/b/c-c:d"
but will match "a/b/c-c:d"
Upvotes: 1