Peter Anderson
Peter Anderson

Reputation: 11

regex: Match word only when another word is not present

I have this Regex

/^(?!(.*(Ink|Cartridge).*))(?:.*(\b - Black$\b))/

Below are my samples

no match string
Simple match string - Black
Unmatched line with lowercase - black
Unmatched line with the word Ink within - Black
Unmatched line with the word Cartridge within - Black
Unmatched line with the string' - Black' before the end

My regex matches the entire line 2, but I am trying to match just the word ' - Black' at the end of the string and not the entire string.

The regular expression syntax should be based on JavaScript regular expressions.

any ideas?

Upvotes: 0

Views: 1716

Answers (1)

Jona Rodrigues
Jona Rodrigues

Reputation: 980

If you need to match the word '-Black' only, the correct regex would be:

/- Black/

The regex above just matches - Black as asked by the question.

However, indeed you have more needs than "matching - Black ", rather you want

all occurrences of the string - Black only when its underlying sentence does not contain Ink nor Cartridge, and only if - Black is at the end of the sentence and not - black (lowercase)

Now, if you just want what I exposed, it is not a problem for you to match ALL the sentence at the same time as the desired - Black string. In fact, this is what capturing is for in the regex world. The parenthesis ( and ) you put in your regex actually "grabs/takes/captures" what's in it for you and STORES it in a variable for later use.

This means :

/hello (world)/

would MATCH hello world but CAPTURE only world. This capture goes into a variable named group, and here I have only one group, so world would be stored in the group number 1.

In order to CALL this group for other purpose (storing/deleting/replacing), you need to write a dollar sign $ followed by the number of the desired group (here 1). For this example, $1 should output world. So this is how you can MATCH something while CAPTURING another.

Thus, coming back to your example. I would suggest you do something like:

/^(?!(?:.*(?:Ink|Cartridge).*))(?:.*(?: (- Black)$))/gm

Look at this regex101, open the substitution tab below the examples, and try to write $1: there you have it,

just - Black.

Then it's up to you to do something with $1.

Upvotes: 1

Related Questions