2015-02-24 20 views
1

我是Go初學者,我一直在玩正則表達式。例如:前往正則表達式:發現後的下一個項目

r, _ := regexp.Compile(`\* \* \*`) 
r2 := r.ReplaceAll(b, []byte("<hr>")) 

(爲<hr>小號更換所有* * * S)

有一兩件事,我不知道怎麼做是occurence後找到next項目。在JavaScript/jQuery的我曾經這樣做:

$("#input-content p:has(br)").next('p').doStuff() 

(查找內部有br標籤p標記後的下一個ptag)。

在Go中完成相同的最簡單的方法是什麼?說,找到* * *之後的下一行?

* * * 

Match this line 

回答

1

你需要使用一個捕獲組中把握了這句話的內容:

package main 

import "fmt" 
import "regexp" 

func main() { 

    str := ` 
* * * 

Match this line 
` 
    r, _ := regexp.Compile(`\* \* \*\n.*\n(.*)`) 

    fmt.Println(r.FindStringSubmatch(str)[1]) 
} 

輸出:

Match this line 

說明:

\* \* \* Matches the first line containing the asterisks. 
\n   A newline. 
.*   Second line. Can be anything (Likely the line is simply empty) 
\n   A newline 
(   Start of capturing group 
.*   The content of interest 
)   End of capturing group 

在評論你問如何<hr/>更換第三行。在這種情況下,我會使用兩個捕獲組 - 一個用於感興趣線之前的部分,另一個用於線本身。在替換模式中,您可以使用$1在結果中使用第一個捕獲組的值。

例子:

package main 

import "fmt" 
import "regexp" 

func main() { 

    str := ` 
* * * 

Match this line 
` 
    r, _ := regexp.Compile(`(\* \* \*\n.*\n)(.*)`) 

    str = string(r.ReplaceAll([]byte(str), []byte("$1<hr/>"))) 

    fmt.Println(str) 
} 
+0

嘿,感謝它的工作。只是一個問題。我用'r.ReplaceAll(b,[] byte(「


」))'代替,但是甚至替換了'* * *'。這是否與代碼中的[1]部分有關?如果是這樣,如何更新我的代碼,以便'* * *'不被替換? – alexchenco 2015-02-24 16:48:50