gpt4 book ai didi

regex - 去正则表达式 : finding next item after an occurence

转载 作者:IT王子 更新时间:2023-10-29 02:16:19 26 4
gpt4 key购买 nike

我是围棋初学者,一直在玩正则表达式。示例:

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

(将所有 * * * 替换为 <hr> s)

我不知道该怎么做的一件事是找到 next发生后的项目。在 JavaScript/jQuery 中,我曾经这样做:

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

(在 p 标签后面找到下一个 tag p,里面有 br 标签)。

在 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)
}

关于regex - 去正则表达式 : finding next item after an occurence,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28697533/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com