Regex to NOT match exact words in a string

Viewed 137

I've the following string:

group.cluster.namespace.release.app.pod.timer.grpc.server.processing.duration.package.method.error.count

and a regex:

(?:[^.]+\.){11}([^.]+)\.([^.]+)\.([^.]+)\.(?:[^.]+)

that produces a match:

Group 1: package
Group 2: method
Group 3: error

Now I want to not match when group 3 is either ok or cancelled. I tried a negative lookahead, but it's not working.

(?:[^.]+\.){11}([^.]+)\.([^.]+)\.(?!ok|cancelled)\.(?:[^.]+)

What is wrong with the regex above?

1 Answers

In your pattern with the negative lookahead, you have to match any char except a dot again in a group.

I would also suggest using wordboundaries to prevent partial matches, and perhaps add an anchor ^ to assert the start of the string.

Note that the negated character classes [^.]+ can also match across newlines. You can exclude newlines using [^.\r\n]+

(?:[^.]+\.){11}([^.]+)\.([^.]+)\.(?!ok\b|cancelled\b)([^.]+)\.(?:[^.]+)

See a regex demo.

Related