Sankar
Sankar

Reputation: 6522

golang regexp find matching strings

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

Answers (2)

ARIF MAHMUD RANA
ARIF MAHMUD RANA

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

Liju
Liju

Reputation: 2303

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

Upvotes: 1

Related Questions