亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

文件中的 Golang 正則表達式精確行

文件中的 Golang 正則表達式精確行

Go
縹緲止盈 2023-03-15 15:29:24
我有一個包含以下內容的文件# Requires authentication with auth-user-passauth-user-pass#auth-user-pass# auth-user-passauth-user-passwd有沒有辦法讓正則表達式只匹配第二行與 Golang?我嘗試使用以下代碼但它返回空切片package mainimport (    "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 回答

?
心有法竹

TA貢獻1866條經驗 獲得超5個贊

您的字符串包含多行,因此您應該打開多行模式(帶有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上嘗試此片段。


查看完整回答
反對 回復 2023-03-15
  • 1 回答
  • 0 關注
  • 119 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號