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

正则表达式-如何在出现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.

  ab1-cde23-fg45-h6-ijk-789.lmn.local。  86400 IN A 12.34.5.123 
  code>  pre> 
 
 

在以下DNS条目中,我试图匹配 h6 code>部分(位置4)。 至此,我知道域的这一部分仅由2个字母/数字或每个字母/数字组成,因此我可以(以笨拙的方式)将其与 p>

   “-[a-zA-Z0-9] {2}-” 
  code>  pre> 
 
 

在我无法假定这是唯一部分的情况下 包含2个字母/数字的域,我怎么才能只匹配第4个位置的内容减去- code>? strong>( ab1 code>是第一个位置, cde23 code>第二个,依此类推,所有位置都由- code>隔开) p>

我能够匹配第4个 p>

 “(([a-zA-Z0-9] *-){3} [a-zA-  Z0-9] *-“ 
  code>  pre> 
 
 

我正在golang中使用这些正则表达式。 p> div>

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