我是Go初学者。我试图将段落与regexp
匹配:
package main
import (
"fmt"
"regexp"
)
func main() {
str := `first paragraph
second paragraph
third paragraph`
r, _ := regexp.Compile(`(.+)(\n\n)`)
fmt.Println(r.FindAllString(str, -1))
}
输出是这样的:
[first paragraph
second paragraph
]
我认为它也匹配空行。我只想匹配段落(first paragraph
,second paragraph
)。
如何修改我的代码来实现这一目标?
答案 0 :(得分:1)
您可以尝试使用re2-compliant regexp,(?s).*?(\n\n|$)
(请参阅playground example):
package main
import (
"fmt"
"regexp"
)
func main() {
str := `first paragraph
second line of first paragraph
second paragraph
third paragraph
second line of third paragraph`
r, _ := regexp.Compile(`(?s).*?(\n\n|$)`)
res := r.FindAllString(str, -1)
fmt.Printf("%+v %d", res, len(res))
}
那会输出:
[first paragraph
second line of first paragraph
second paragraph
third paragraph
second line of third paragraph] 3