英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论