Home > database >  Get text inbetween two items - golang
Get text inbetween two items - golang

Time:03-14

Is it possible to get the text from inside of two "tags" for instance. Lets say you have a string that looks like this:

example text that I don't want
<tag>THIS IS THE TEXT I WANT TO GET</tag>I also don't want this

Would it be possible to just take that 'THIS IS THE TEXT I WANT TO GET' part?

I have asked around and not found much help :/

CodePudding user response:

It depends on how complex is the structure of your input data.

If it is as simple as in your example, having a single pair of <tag> and </tag>, you could use code like this:

func extract(input, tagBegin, tagEnd string) string {
    begin := strings.Index(input, tagBegin)
    if begin < 0 {
        return ""
    }
    begin  = len(tagBegin)
    end := strings.Index(input[begin:], tagEnd)
    if end < 0 {
        return ""
    }
    return input[begin : begin end]
}

Test it on playground

CodePudding user response:

Use regular expressions.

package main

import (
    "fmt"
    "regexp"
)

func main() {
    r, _ := regexp.Compile("<tag>(.*)<\\/tag>")
    s :=    `example text that I don't want
    <tag>THIS IS THE TEXT I WANT TO GET</tag>I also don't want this example text that I don't want
    <tag>THIS IS THE TEXT I ALSO WANT TO GET</tag>I also don't want this`
    arr := r.FindAllStringSubmatch(s, -1)
    fmt.Println(arr[0][1])
    fmt.Println(arr[1][1])
}
  •  Tags:  
  • go
  • Related