dryeyhe0266 2015-02-24 13:49
浏览 41
已采纳

正则表达式:发生后查找下一项

I'm a Go beginner and I've been playing with regexes. Example:

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

(Replace all * * *s for <hr>s)

One thing that I have no idea how to do is to find the next item after an occurence. In JavaScript/jQuery I used to do this:

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

(Find the next p tag after a p tag that has a br tag inside).

What's the simplest way to accomplish the same in Go? Say, finding the next line after * * * ?

* * *

Match this line
  • 写回答

1条回答 默认 最新

  • douwen0612 2015-02-24 14:21
    关注

    You would need to use a capturing group to grap the contents of that sentence:

    package main
    
    import "fmt"
    import "regexp"
    
    func main() {
    
        str := `
    * * *
    
    Match this line
    `   
        r, _ := regexp.Compile(`\* \* \*
    .*
    (.*)`)
    
        fmt.Println(r.FindStringSubmatch(str)[1])
    }
    

    Output:

    Match this line
    

    Explanation:

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

    In comments you asked how to replace the third line by <hr/>. In this case I would use two capturing groups - one for the part before the line of interest and one for the line itself. In the replacement pattern you can then use $1 to use the value of the first capturing group in the result.

    Example:

    package main
    
    import "fmt"
    import "regexp"
    
    func main() {
    
        str := `
    * * * 
    
    Match this line
    `   
        r, _ := regexp.Compile(`(\* \* \*
    .*
    )(.*)`)
    
        str = string(r.ReplaceAll([]byte(str), []byte("$1<hr/>")))
    
        fmt.Println(str)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向