Golang正则表达式在文件中精确匹配行

huangapple go评论77阅读模式
英文:

Golang regex exact line in file

问题

我有一个包含以下内容的文件:

# 需要使用 auth-user-pass 进行身份验证
auth-user-pass
#auth-user-pass
# auth-user-pass
auth-user-passwd

有没有办法使用 Golang 的正则表达式只匹配第二行?

我尝试了以下代码,但它返回一个空切片:

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
[]
英文:

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
[]

答案1

得分: 1

你的字符串包含多行,所以你应该打开多行模式(使用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)
}

你可以在这个链接上尝试这个代码片段:https://play.golang.com/p/6au1_K2ImBt。

英文:

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

Here is a quick example :

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.

huangapple
  • 本文由 发表于 2022年11月18日 23:39:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/74492025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定