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 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上
  • ¥15 向数据表用newid方式插入GUID问题
  • ¥15 multisim电路设计
  • ¥20 用keil,写代码解决两个问题,用库函数
  • ¥50 ID中开关量采样信号通道、以及程序流程的设计
  • ¥15 U-Mamba/nnunetv2固定随机数种子
  • ¥15 vba使用jmail发送邮件正文里面怎么加图片
  • ¥15 vb6.0如何向数据库中添加自动生成的字段数据。