dongyuyi5680 2017-01-31 04:53
浏览 18
已采纳

正则表达式-如何在出现X个模式后匹配子字符串?

ab1-cde23-fg45-h6-ijk-789.lmn.local.        86400 IN A  12.34.5.123

In the follow DNS entry, I'm trying to match the h6 section (position 4). At this point, I know this section of the domain is only composed of 2 letters/digits or one of each, so I can match it (in a clumsy way) with

"-[a-zA-Z0-9]{2}-"

In a case where I could not assume that this is the only section of a domain with 2 letters/digits, how could I match only the content of the 4th position minus the -? (ab1 being the first position, cde23 the second, and so on, with all the positions separated by -)

I'm able to match up to the 4th positions with the following regex, but it includes everything from the start.

"([a-zA-Z0-9]*-){3}[a-zA-Z0-9]*-"

I'm using theses regexp in golang.

  • 写回答

1条回答 默认 最新

  • dsnhalq37505 2017-01-31 04:57
    关注

    Do:

    ^(?:[^-]+-){3}([^-]+)
    
    • ^(?:[^-]+-){3} matches - separated first 3 fields, (?:) makes the group non-capturing

    • The captured group, ([^-]+) will contain the - separated 4th field.

    Demo


    While we are at this, you should perhaps look at string manipulation rather than costly Regex implementation, plain strings.Split() should do:

    package main
    
    import (
        "fmt"
        "strings"
    )
    
    func main() {
        s := "ab1-cde23-fg45-h6-ijk-789.lmn.local.        86400 IN A  12.34.5.123"
        fmt.Println(strings.Split(s, "-")[3])
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100