捕获两个大括号之间的所有数据。

huangapple go评论83阅读模式
英文:

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

huangapple
  • 本文由 发表于 2016年4月13日 02:17:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/36581093.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定