登录
首页 >  Golang >  Go问答

使用Golang的正则表达式来精确匹配文件中的行

来源:stackoverflow

时间:2024-03-20 23:48:41 153浏览 收藏

使用正则表达式精确匹配文件中的行时,若文本包含多行,需开启多行模式(`(?m)`)。文章中,用户使用 `regexp.compile(`^auth-user-pass$`)` 匹配文件中的行,但未开启多行模式,导致只匹配到空行。通过使用 `(?m)^auth-user-pass$` 开启多行模式,正则表达式能够成功匹配目标行。

问题内容

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

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

正确答案


您的字符串包含多行,因此您应该打开多行模式(使用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.

到这里,我们也就讲完了《使用Golang的正则表达式来精确匹配文件中的行》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>