I'm a Go beginner. I'm trying to match paragraphs with regexp
:
package main
import (
"fmt"
"regexp"
)
func main() {
str := `first paragraph
second paragraph
third paragraph`
r, _ := regexp.Compile(`(.+)(
)`)
fmt.Println(r.FindAllString(str, -1))
}
The output is this:
[first paragraph
second paragraph
]
I think it's matching the empty lines also. I only want to match the paragraphs (first paragraph
, second paragraph
).
How to modify my code to accomplish that?
You can try, using a re2-compliant regexp, (?s).*?( |$)
(see 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).*?(
|$)`)
res := r.FindAllString(str, -1)
fmt.Printf("%+v %d", res, len(res))
}
That would output:
[first paragraph
second line of first paragraph
second paragraph
third paragraph
second line of third paragraph] 3