试图读取包含在两个大括号内的所有数据。我怀疑我的正则表达式失败,因为它无法匹配换行符。go 操场中的源链接:http : //play.golang.org/p/uNjd01CL8Zpackage mainimport ( "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))}
1 回答

大话西游666
TA贡献1817条经验 获得超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 正则表达式的正则表达式语法文档的链接:https : //github.com/google/re2/wiki/Syntax
- 1 回答
- 0 关注
- 177 浏览
添加回答
举报
0/150
提交
取消