Home > Mobile >  Regex for Negative Lookbehind in Golang
Regex for Negative Lookbehind in Golang

Time:09-06

I want to match string that contain "server-key" but not if the string start with "test-"

For example input:

1. dummy "test-server-key-asd" dummy
2. dummy "server-key-qwe" dummy
3. server-key-wer
4. a server-key-ert
5. test-server-key

The output will be

server-key-qwe
server-key-wer
server-key-ert

With a negative lookbehind, the regex will be (?<!test-)server-key-[a-z]{3}

What is the alternative negative lookbehind for this regex in Go? because Go doesn't support negative lookbehind.

CodePudding user response:

Workaround

Effectively, you cannot use negative lookbehind. But you could capture what's before and after to see if it's only server-key, surounded by spaces, simple or double quotes:

(^|[\s"'])(server-key)([\s"']|$)

I added ^ at the beginning and $ and the end, in case your match isn't surounded by spaces or quotes.

You could then just use capture group 2 and forget group 1 and 3.

Playing around here: https://regex101.com/r/grRpZC/1

This way you cannot match something like server-keys or mysql-server-key which I imagine you don't want to match.

Workaround improved

But the solution isn't very bullet proof since we probably could have server-key surounded by some other chars, such as [](){}%*.... And we don't want to list them all. But we could say that server-key should not be surounded by any non-latin char, hyphen or number. This can be done with the help of \p{L} (or \p{Letter}) which matches any letter from any language. It's probably better than using [a-z] in case of accents or whatever.

We don't want to match letters, hyphens or numbers, so this would be: [^\p{L}\d-]

Putting it back into the regex we get:

(^|[^\p{L}\d-])(server-key)([^\p{L}\d-]|$)

Full test here: https://regex101.com/r/1oPZXb/1

CodePudding user response:

There is no way in Golang using only regex.

But this regex will capture the target including any prefix

[a-z-]*server-key-[a-z]{3}

Then test that what's captured doesn't start with "test-":

if !strings.HasPrefix(s, "test-")
  • Related