Golang regular expression splits string based on keywords

WBOY
Release: 2024-02-10 15:15:08
forward
795 people have browsed it

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
Copy after login

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)
}
Copy after login

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]
Copy after login

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)(.+)`)
Copy after login

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!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!