[英]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.在上面的程序中,我想要:
a
, b
, cc
和d
作为单独的元素打印。 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 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.