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.
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
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) }
$ go run main.go []
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) }
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!