试图读取包含在两个大括号内的所有数据。我怀疑我的regex失败了,因为它不能匹配换行符。链接到go游乐场中的源:http://play.golang.org/p/uNjd01CL8Z
package main
import (
"fmt"
"regexp"
)
func main() {
x := `
lease {
interface "eth0";
fixed-address 10.11.0.1;
option subnet-mask 255.255.0.0;
}
lease {
interface "eth0";
fixed-address 10.11.0.2;
option subnet-mask 255.255.0.0;
}
lease {
interface "eth0";
fixed-address 10.11.0.2;
option subnet-mask 255.255.0.0;
}`
re := regexp.MustCompile(`{(.+)?}`)
fmt.Println(re.FindAllString(x, -1))
}发布于 2016-04-12 18:39:14
这里有一个解决方案:
package main
import (
"fmt"
"regexp"
)
func main() {
x := `
lease {
interface "eth0";
fixed-address 10.11.0.1;
option subnet-mask 255.255.0.0;
}
lease {
interface "eth0";
fixed-address 10.11.0.2;
option subnet-mask 255.255.0.0;
}
lease {
interface "eth0";
fixed-address 10.11.0.2;
option subnet-mask 255.255.0.0;
}`
re := regexp.MustCompile(`(?s){.*?}`)
fmt.Println(re.FindAllString(x, -1))
}我改变了两件事。(?s)标志意味着它也将匹配.通配符的换行符。.*?意味着在大括号之间匹配的字符要少于更多的字符。如果要使用.*,它将与大括号的外部对匹配。
下面是用于Go正则表达式的regex语法文档的链接:https://github.com/google/re2/wiki/Syntax
https://stackoverflow.com/questions/36581093
复制相似问题