2015-03-03 57 views
1

我是Go初學者。我試圖用regexp匹配的段落:在Go中匹配段落

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

你需要匹配'第三paragraph'嗎?或者只是第一個2? – 2015-03-03 08:41:47

+0

@ʰᵈˑ是的,我剛剛意識到這個問題。現在不需要。我會在稍後解決。 – alexchenco 2015-03-03 09:01:48

+1

是否是正則表達式的一個要求?看起來過度... – 2015-03-03 09:16:27

回答

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