Golang 正则表达式解析 API 路径
Golang 正则表达式解析 API 路径
本文介绍如何使用 Golang 正则表达式解析 API 路径,将字符串例如 '/gocloud.api.wms.v1.hello.HelloService/Read' 分解成 '/gocloud.api.wms.v1.', 'hello.HelloService' 和 'Read' 三部分。
代码示例:
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile(`^/([^/]+)/([^/]+)$`)
str1 := "/gocloud.api.wms.v1.hello.HelloService/Read"
str2 := "/xxx.aaa.Xxx/Gaa"
fmt.Println(reg.FindStringSubmatch(str1))
fmt.Println(reg.FindStringSubmatch(str2))
}
解析:
regexp.MustCompile(^/([^/]+)/([^/]+)$): 定义正则表达式,匹配以 '/' 开头的字符串,并将第一个 '/' 后的内容和第二个 '/' 后的内容分别捕获到两个分组中。reg.FindStringSubmatch(str1)和reg.FindStringSubmatch(str2): 使用正则表达式匹配字符串,并将匹配结果以数组形式返回,数组的第一项是整个匹配结果,后面的项是每个分组的匹配结果。
结果:
[/gocloud.api.wms.v1. hello.HelloService Read]
[/xxx.aaa.Xxx Gaa]
总结:
本示例展示了使用 Golang 正则表达式解析 API 路径的方法,方便开发者将 API 路径信息分解成不同的部分进行处理。
原文地址: https://www.cveoy.top/t/topic/lh3A 著作权归作者所有。请勿转载和采集!