You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Golang正则匹配文件中独立的auth-user-pass行?

问题原因与解决方案

你的正则没匹配到目标行,核心问题是Golang标准库的regexp默认是单行模式:

  • ^在单行模式下匹配整个字符串的开头,而非每行开头
  • $匹配整个字符串的结尾,而非每行结尾

你的文件内容是多行字符串,第二行的auth-user-pass既不在整个字符串的首尾,所以原正则完全匹配不到。

解决方法:启用多行模式

在正则开头加上(?m)标志,开启多行模式后,^和$就会匹配每行的首尾。修改后的正则为:(?m)^auth-user-pass$

修改后的完整代码

package main

import (
    "fmt"
    "os"
    "regexp"
)

func main() {
    bytes, err := os.ReadFile("file.txt")
    if err != nil {
        panic(err)
    }

    // 启用多行模式,匹配纯"auth-user-pass"的行
    re, _ := regexp.Compile(`(?m)^auth-user-pass$`)
    matches := re.FindAllString(string(bytes), -1)
    fmt.Println(matches)
}

运行结果

$ go run main.go
[auth-user-pass]

这个正则会精准匹配第二行,因为:

  • 第三行是#auth-user-pass,开头多了#,不满足^auth-user-pass$
  • 第四行是# auth-user-pass,开头多了# ,不满足
  • 第五行是auth-user-passwd,结尾多了wd,不满足

内容的提问来源于stack exchange,提问作者Prasta Maha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 03:05:23