英文:
Capture all data between two braces
问题
尝试读取两个花括号之间的所有数据。我怀疑我的正则表达式失败是因为它无法匹配换行符。在go playground中的源代码链接: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))
}
英文:
Trying to read all data enclosed within two curly braces. I suspect my regex fails because it cannot match newlines. Link to source in go playground: 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))
}
答案1
得分: 1
这是一个解决方案:
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
英文:
Here's a solution:
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))
}
I changed two things. The (?s)
flag means that it will match newlines as for .
wildcards as well. And the .*?
means that it will rather match fewer than more characters between the braces. If you would use .*
, it would match the outer pair of braces instead.
Here's the link to the documentation of the regex syntax used for Go regular expressions: https://github.com/google/re2/wiki/Syntax
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论