首页  >  文章  >  后端开发  >  Golang正则表达式文件中的精确行

Golang正则表达式文件中的精确行

WBOY
WBOY转载
2024-02-08 21:06:30938浏览

Golang正则表达式文件中的精确行

Golang是一种强大的编程语言,其内置的正则表达式功能为处理文本文件提供了便利。在Golang中,使用正则表达式可以实现对文件中特定行的匹配和提取。本文由php小编小新为读者介绍了如何使用Golang的正则表达式功能精确匹配文件中的行,并给出了实际的代码示例。通过学习本文,读者将能够更好地理解和应用Golang中的正则表达式功能,提高文件处理的效率和准确性。

问题内容

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

# 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://www.php.cn/link/f4f4a06c589ea53edf4a9b18e70bbd40.

以上是Golang正则表达式文件中的精确行的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:stackoverflow.com。如有侵权,请联系admin@php.cn删除