Home >Backend Development >Golang >Golang regular expression splits string based on keywords

Golang regular expression splits string based on keywords

WBOY
WBOYforward
2024-02-10 15:15:08834browse

Golang regular expression splits string based on keywords

php editor Apple introduces you a powerful string processing technique - golang regular expression to split strings based on keywords. In development, we often need to split the string according to a certain keyword in order to further process the data. By using golang's regular expressions, we can easily implement this function and improve development efficiency. This article will introduce you in detail how to use golang regular expressions and how to split strings according to keywords, helping you to process strings more flexibly in daily development. Let’s explore together!

Question content

This is my string like findstudentbyid Now I will base the find## before the word find Split the keywords before the word and by and by , id.

So the golang regular expression pattern is

`(?i)(^find{1})(\w )(by{1})(\w )`

I'm trying to split this keyword

findstudentbyid but I'm having trouble finding the exact results I'm finding. My expected output is [Find student by id] or

find
student
by
id

But I can't do this. I did try this 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)
}

Solution

I don't think

Regexp.Split() is a suitable solution for your situation, according to the documentation:

I think what you need is to find submatches (like

find, student, by and id):

So you can use

Regexp.FindStringSubmatch() like this:

fmt.Println("result: ", re.FindStringSubmatch(txt))

result: [findstudentbyid find student by id]

I also think you can simplify the regex, but don't forget to put it in parentheses to handle submatches, like pointed out in the comments:

re := regexp.MustCompile(`(find)(.+)(by)(.+)`)

The above is the detailed content of Golang regular expression splits string based on keywords. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete