Golang 正则表达式:解析 API 路径

本文介绍使用 Golang 正则表达式解析 API 路径,例如将 '/gocloud.api.wms.v1.hello.HelloService/Read' 解析成 'hello.HelloService' 和 'Read',以及 '/xxx.aaa.Xxx/Gaa' 解析成 'aaa.Xxx' 和 'Gaa'。

正则表达式:

([^/]+)/([^/]+)

解释:

  • ([^/]+): 匹配非'/'字符的一个或多个,并将其捕获到第一个分组。
  • /: 匹配'/'字符。
  • ([^/]+): 匹配非'/'字符的一个或多个,并将其捕获到第二个分组。

示例代码:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`([^/]+)/([^/]+)`)
	str := `/gocloud.api.wms.v1.hello.HelloService/Read`
	matches := re.FindStringSubmatch(str)
	if len(matches) > 0 {
		fmt.Println("Service: ", matches[1])
		fmt.Println("Method: ", matches[2])
	}
}

输出:

Service:  hello.HelloService
Method:  Read

总结:

使用 Golang 正则表达式可以方便地解析 API 路径,提取出所需的组件,如服务名和方法名。您可以根据实际情况调整正则表达式,以满足不同的解析需求。

Golang 正则表达式:解析 API 路径

原文地址: https://www.cveoy.top/t/topic/lh3b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录