Rory
Rory

Reputation: 41827

How do i write a Regular Expression to match text containing XYZ but not ABC?

I want to write a regex that matches if a string contains XYZ but doesn't contain ABC somewhere before it. So "blah XYZ blah" should match, but "blah ABC blah XYZ blah " should not.

Any ideas? In particular I'm writing the regex in c#, in case there's anything specific to that syntax.

I guess I can use negative lookbehind but haven't used this before...

thanks!

UPDATE: I need a regex as I don't have the ability to modify the code, just some configuration.

UPDATE: Changed as I actually only need to check that ABC doesn't appear before XYZ, I don't need to check if it comes after.

Upvotes: 2

Views: 1876

Answers (5)

Alan Moore
Alan Moore

Reputation: 75232

No need for lookbehind:

^(?:(?!ABC).)*XYZ

Upvotes: 2

Gumbo
Gumbo

Reputation: 655319

This should work:

^(?:(?!ABC).{3,})?XYZ

And if it also should not appear after XYZ:

^(?:(?!ABC).{3,})?XYZ(?:.{3,}(?<!ABC))?$

Upvotes: 0

PhiLho
PhiLho

Reputation: 41142

^(?:(?<!ABC).)*XYZ

was fine for my little testset.

Upvotes: 4

empi
empi

Reputation: 15881

that should do the trick:

^([^(ABC)]*)(XYZ)(.*)$

some examples:

sadsafjaspodsa //False
sadABCdsaABCdsa //False
sadABCdsaABCdsaXYZ //False
sadABCdsaABCdsaXYZaa //False
sadABCddasABCsaXYZdsa //False
sadsaXYZdsa //True
sadsaXYZ //True

Upvotes: 0

Jimmy
Jimmy

Reputation: 91472

is there anything wrong with

 string.Contains("XYZ") && !string.contains("ABC") 

Upvotes: 2

Related Questions