我有一個包含以下內容的檔案
# Requires authentication with 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
[]
uj5u.com熱心網友回復:
您的字串包含多行,因此您應該打開多行模式(帶有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上嘗試此片段。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/536820.html
上一篇:Bash替換從命令末尾傳遞
下一篇:根據命令列過濾“頂級”命令結果
