Home > other >  Go: regexp matching a pattern AND then another pattern
Go: regexp matching a pattern AND then another pattern

Time:11-04

I have the following Golang code:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    // dummy text data
    blob := `
    #s-kiwi
    foo
    #e-kiwi
    #s-banana
        bar
    #e-banana
    #s-mango
    baz
    #e-mango
    `

    // try to match two lines
    fruit := "banana"
    result, _ := regexp.MatchString("#[se]-" fruit, blob)
    fmt.Println(result)
}

Go playground link: https://go.dev/play/p/p9Q4HYijx9m

I am trying to achieve a full matching with the usage of an AND property. I would like to search for, the pattern #s-banana AND #e-banana just to ensure that the blob text has its enclosing and initiator parameters.

What I have tried is using regexp.MatchString("#[se]-" fruit, blob) but "#[se]-" only matches characters s OR e.

Could this be implemented in a oneliner? Should I add a new regexp condition? If that's the case this does not seem quite polished.

What my desired result is:

Trying to search for two strings in text with regexp on golang using an AND condition.

Many thanks.

CodePudding user response:

It's not completely clear what you are trying to do. But assuming you want to confirm the multiline text contains a pair of tags starting with #s-banana and ending with #e-banana you can search for that, with any number of characters inbetween:

result, _ := regexp.MatchString("(?s)#s-" fruit ".*?#e-" fruit, blob)

That returns true. The initial (?s) allows . to match newlines too, and the .*? matches the shortest sequence of zero or more characters including newlines.

  • Related