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

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

Golang regex exact line in file

问题

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

  1. # 需要使用 auth-user-pass 进行身份验证
  2. auth-user-pass
  3. #auth-user-pass
  4. # auth-user-pass
  5. auth-user-passwd

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

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

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "regexp"
  6. )
  7. func main() {
  8. bytes, err := os.ReadFile("file.txt")
  9. if err != nil {
  10. panic(err)
  11. }
  12. re, _ := regexp.Compile(`^auth-user-pass$`)
  13. matches := re.FindAllString(string(bytes), -1)
  14. fmt.Println(matches)
  15. }
  1. $ go run main.go
  2. []
英文:

I have a file with below content

  1. # Requires authentication with auth-user-pass
  2. auth-user-pass
  3. #auth-user-pass
  4. # auth-user-pass
  5. 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

  1. package main
  2. import (
  3. "fmt"
  4. "os"
  5. "regexp"
  6. )
  7. func main() {
  8. bytes, err := os.ReadFile("file.txt")
  9. if err != nil {
  10. panic(err)
  11. }
  12. re, _ := regexp.Compile(`^auth-user-pass$`)
  13. matches := re.FindAllString(string(bytes), -1)
  14. fmt.Println(matches)
  15. }
  1. $ go run main.go
  2. []

答案1

得分: 1

你的字符串包含多行,所以你应该打开多行模式(使用m标志):

这是一个快速的示例:

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. var str = `# Requires authentication with auth-user-pass
  8. auth-user-pass
  9. #auth-user-pass
  10. # auth-user-pass
  11. auth-user-passwd`
  12. re, _ := regexp.Compile(`(?m)^auth-user-pass$`)
  13. matches := re.FindAllString(str, -1)
  14. fmt.Println(matches)
  15. }

你可以在这个链接上尝试这个代码片段: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 :

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main() {
  7. var str = `# Requires authentication with auth-user-pass
  8. auth-user-pass
  9. #auth-user-pass
  10. # auth-user-pass
  11. auth-user-passwd`
  12. re, _ := regexp.Compile(`(?m)^auth-user-pass$`)
  13. matches := re.FindAllString(str, -1)
  14. fmt.Println(matches)
  15. }

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:

确定