Golang 正则表达式解析路径字符串
Golang 正则表达式解析路径字符串/n/n本文将展示如何使用 Golang 正则表达式解析类似 '/gocloud.api.wms.v1.hello.HelloService/Read' 这样的路径字符串,并将其拆分成两部分:'hello.HelloService' 和 'Read'。/n/ngo/npackage main/n/nimport (/n/t/'fmt/'/n/t/'regexp/'/n)/n/nfunc main() {/n/tstr1 := '/gocloud.api.wms.v1.hello.HelloService/Read'/n/tstr2 := '/xxx.aaa.Xxx/Gaa'/n/treg := regexp.MustCompile(`'/(/w+/./w+/./w+)/.(/w+)/.(/w+)//(/w+)'`) // 使用单引号包裹正则表达式/n/tmatch1 := reg.FindStringSubmatch(str1)/n/tmatch2 := reg.FindStringSubmatch(str2)/n/tfmt.Printf('%s.%s %s/n', match1[1], match1[3], match1[4])/n/tfmt.Printf('%s.%s %s/n', match2[1], match2[3], match2[4])/n}/n/n/n代码解析:/n/n1. 定义两个字符串 str1 和 str2,分别代表需要解析的路径字符串。/n2. 使用 regexp.MustCompile() 函数编译正则表达式 '/(/w+/./w+/./w+)/.(/w+)/.(/w+)//(/w+)'。该正则表达式匹配以 '/' 开头的字符串,并将匹配到的部分分别存储在四个捕获组中。/n3. 使用 reg.FindStringSubmatch() 函数在字符串中查找匹配的子字符串,并将匹配到的结果存储在 match1 和 match2 中。/n4. 最后使用 fmt.Printf() 函数输出解析后的结果。/n/n输出结果:/n/n/ngocloud.api.wms.hello.HelloService Read/nxxx.aaa.Xxx Gaa/n/n/n注意:/n/n* 使用单引号包裹正则表达式,以避免与 Go 代码中的双引号冲突。/n* 正则表达式中的 /w+ 表示匹配一个或多个单词字符。/n* 捕获组的索引从 1 开始,所以 match1[1] 表示第一个捕获组,match1[3] 表示第三个捕获组,以此类推。/n/n其他解析方法:/n/n除了使用正则表达式,还可以使用 strings.Split() 等函数进行字符串分割来解析路径字符串。但正则表达式提供更灵活的匹配模式,可以根据需要修改正则表达式来满足不同的解析需求。
原文地址: https://www.cveoy.top/t/topic/lh3m 著作权归作者所有。请勿转载和采集!