1

I have the following string:

my-name-host1.host2.host3.com:80

I'm looking for a regex which matches everything until the string -host1.host2.host3.com:80, i.e. the result shall be:

my-name

My current regex in JavaScript seems to be working. The problem is that I need this regex in a "Golang flavor".

https://regex101.com/r/ebSTuq/1

When switching it to Golang I get this regex with a pattern error:
.*(?=\Q-host1.host2.host3.com:80\E)

The preceding token is not quantifiable.

Robert Strauch
  • 12,055
  • 24
  • 120
  • 192

1 Answers1

1

Go regex engine is RE2, and RE2 does not support lookarounds.

Actually, you do not need the lookahead: use the non-greedy dot pattern at the start, capture it into Group 1 and use the rest of the pattern as is to check the right hand context:

str := `my-name-host1.host2.host3.com:80`
re := regexp.MustCompile(`(.*?)-host1\.host2\.host3\.com:80`)
match := re.FindStringSubmatch(str)
fmt.Println(match[1]) 

Output: my-name, see the Go demo.

Note the use of the FindStringSubmatch function that allows access to captured substrings.

Also, see the Go regex demo.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563