简体   繁体   English

golang regexp 查找匹配的字符串

[英]golang regexp find matching strings

I have strings of the format %s/%s/%s:%s where there are four substrings.我有%s/%s/%s:%s格式的字符串,其中有四个子字符串。 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 , cc and d to be printed as individual elements.在上面的程序中,我想要: abccd作为单独的元素打印。 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.整个字符串作为FindAllStringSubmatch返回的数组的第一个元素返回。 What is the way to extract the individual elements that match the regex ?提取与正则表达式匹配的单个元素的方法是什么?

Playground link: https://play.golang.org/p/M1sKGl0n2tK游乐场链接: https : //play.golang.org/p/M1sKGl0n2tK

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.尝试使用下面的正则表达式来匹配字符串并使用 $1,$2,$3,$4 来匹配单个字符串。

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

Demo演示

Use split as it's pattern is fixed you know it's : separated then / separated regex is expensive CPU process使用 split 因为它的模式是固定的,你知道它是:分离然后/分离的正则表达式是昂贵的 CPU 进程

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 & 如果您更喜欢使用正则表达式,那么也可以在开头使用完整匹配^ & 在结尾使用$

"^([^/]+)/([^/]+)/([^/]+):([^:]+)$"

eg this will not match "a/a/b/cc:d" but will match "a/b/cc:d"例如,这不会匹配"a/a/b/cc:d"但会匹配"a/b/cc:d"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM