Quasipickle
Quasipickle

Reputation: 4498

Regex with double negative matches

Given a series of strings:

I want to write a regex that will match anything not starting with error, and that also doesn't have .user in it. So for this list, success and success.admin

What I've got so far is: /^((?!error)\w*)((?!\.*user)\w*)/

The first part: ((?!error)\w*) is working fine, and narrowing down the matches to just strings that start with success. For some reason the second part: ((?!\.*user)\w*) is doing precisely nothing. I think the first part is matching too much.

I'm doing this in PHP/PCRE
Here's my regex101.com link: https://regex101.com/r/l2sZru/1

Upvotes: 3

Views: 977

Answers (1)

anubhava
anubhava

Reputation: 785156

You need to fix your negative regex like this:

^(?!error|.*\.user)[\w.]+$

RegEx Demo

Here (?!error|.*\.user) will assert failure if error is at the start OR if .user` is found anywhere in the input.

(?!\.*user) in your regex means assert failure when input has 0 or more DOTs followed by user at the start only.

Upvotes: 2

Related Questions