0

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

1

2 Answers 2

1

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"

Sign up to request clarification or add additional context in comments.

Comments

1

Use captured group to extract individual strings.
Try below regex to match the string and use $1,$2,$3,$4 to get individual strings matched.

(.+)/(.+)/(.+):(.+)

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.