Home > Blockchain >  Golang regex exact line in file
Golang regex exact line in file

Time:11-19

I have a file with below content

# Requires authentication with auth-user-pass
auth-user-pass
#auth-user-pass
# auth-user-pass
auth-user-passwd

Is there any way to regex only match the second line with Golang?

I have tried with following code but it return empty slice

package main

import (
    "fmt"
    "os"
    "regexp"
)

func main() {
    bytes, err := os.ReadFile("file.txt")
    if err != nil {
        panic(err)
    }

    re, _ := regexp.Compile(`^auth-user-pass$`)
    matches := re.FindAllString(string(bytes), -1)
    fmt.Println(matches)
}
$ go run main.go
[]

CodePudding user response:

Your string contains multiple line, so you should turn on the multiline mode (m) :

package main

import (
    "fmt"
    "regexp"
)

func main() {
    var str = `# Requires authentication with auth-user-pass
auth-user-pass
#auth-user-pass
# auth-user-pass
auth-user-passwd`

    re, _ := regexp.Compile(`(?m)^auth-user-pass$`)
    matches := re.FindAllString(str, -1)
    fmt.Println(matches)
}

You can try this snippet on : https://play.golang.com/p/6au1_K2ImBt.

  • Related