Exact line in Golang regex file

WBOY
Release: 2024-02-08 21:06:30
forward
951 people have browsed it

Exact line in Golang regex file

Golang is a powerful programming language whose built-in regular expression functionality provides convenience for processing text files. In Golang, regular expressions can be used to match and extract specific lines in files. This article by PHP editor Xiaoxin introduces readers to how to use Golang's regular expression function to accurately match lines in a file, and gives actual code examples. By studying this article, readers will be able to better understand and apply the regular expression function in Golang, and improve the efficiency and accuracy of file processing.

Question content

I have a file containing the following content

# requires authentication with auth-user-pass
auth-user-pass
#auth-user-pass
# auth-user-pass
auth-user-passwd
Copy after login

Is there a way to make the regular expression match only the second line with golang?

I tried using the following code but it returns 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)
}
Copy after login
$ go run main.go
[]
Copy after login


Correct answer


Your string contains multiple lines, so you should turn on multiline mode (using m sign):

This is a simple 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)
}
Copy after login

You can try this code snippet at: https://www.php.cn/link/f4f4a06c589ea53edf4a9b18e70bbd40.

The above is the detailed content of Exact line in Golang regex file. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!