这是我的字符串,如 findstudentbyid
现在,我将根据 find
单词之前的 find
单词和 by< 之后的单词进行拆分
和 by
、id
。
所以 golang 正则表达式模式是 `(?i)(^find{1})(\w+)(by{1})(\w+)`
我正在尝试拆分此关键字 findstudentbyid
但我遇到问题,无法找到我正在查找的确切结果。
我的预期输出是 [通过 id 查找学生]
或
find
student
by
id
但我无法做到这一点。我确实尝试过这个golang code
package main
import (
"fmt"
"regexp"
)
func main() {
txt := "findstudentbyid"
re := regexp.MustCompile(`(?i)(^find{1})(\w+)(by{1})(\w+)`)
split := re.Split(txt, -1)
set := []string{}
for i := range split {
set = append(set, split[i])
}
fmt.Println(set)
}
最佳答案
我认为 Regexp.Split()
不是适合您情况的解决方案,according to the documentation :
The slice returned by this method consists of all the substrings of s not contained in the slice returned by FindAllString.
我猜你需要的是找到子匹配(如find
、student
、by
和id
):
Submatch 0 is the match of the entire expression, submatch 1 is the match of the first parenthesized subexpression, and so on.
所以你可以像这样使用Regexp.FindStringSubmatch()
:
fmt.Println("result: ", re.FindStringSubmatch(txt))
result: [findstudentbyid find student by id]
我还认为您可以简化正则表达式,但不要忘记将其放入括号中来处理子匹配,就像注释中指出的那样:
re := regexp.MustCompile(`(find)(.+)(by)(.+)`)
关于regex - golang正则表达式根据关键字分割字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77167912/