Regex - How to match a substring after X occurrences of a pattern?

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

In the next DNS record, I am trying to map the h6 partition (position 4). At the moment, I know that this domain section consists of only two letters / numbers or one at a time, so I can match it (awkwardly) with

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

In the case when I could not assume that this is the only domain section with two letters / numbers, how can I compare only the contents of the 4th position minus - ? ( ab1 - first position, cde23 second, etc. with all positions divided by - )

I can match 4 positions with the following regex, but it includes everything from the start.

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

I am using regexp tags in golang.

+5
source share
1 answer

make:

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

  • The captured group ([^-]+) will contain a divided - 4th field.

Demo


While we are in this matter, you should probably look at string manipulations and not at the expensive Regex implementation, a simple 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]) } 
+6
source

Source: https://habr.com/ru/post/1263611/


All Articles