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)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘