regex - golang正则表达式根据关键字分割字符串

标签 regex go regex-group

这是我的字符串,如 findstudentbyid 现在,我将根据 find 单词之前的 find 单词和 by< 之后的单词进行拆分byid

所以 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.

我猜你需要的是找到子匹配(如findstudentbyid ):

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/

相关文章:

regex - 带有 $> 符号的正则表达式

javascript - 用于解析数学表达式的正则表达式?

json - 使用 redigo 从 Redis 将 json 部分转换为 Go 结构

java - 转义字符之间的字符串的正则表达式

go - 使用 Go 获取目录中的文件数

mysql - 执行 SQL "dry run"(来自 Go 应用程序)

正则表达式检测任何重复的字符,但之间有可选的空格

javascript - 如何合并后面没有空格的点(.)? [正则表达式]

regex - 如何使用正则表达式解析可变长度命令行参数?

c++ - 使用 std::regex_token_iterator(不一定)查找单词以查找字符串中的字符位置