前往正则表达式:发现后的下一个项目
问题描述:
我是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
标记后的下一个p
tag
)。
在Go中完成相同的最简单的方法是什么?说,找到* * *
之后的下一行?
* * * Match this line
答
你需要使用一个捕获组中把握了这句话的内容:
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)
}
嘿,感谢它的工作。只是一个问题。我用'r.ReplaceAll(b,[] byte(“
”))'代替,但是甚至替换了'* * *'。这是否与代码中的[1]部分有关?如果是这样,如何更新我的代码,以便'* * *'不被替换? – alexchenco 2015-02-24 16:48:50