Reputation: 41827
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
Reputation: 655319
This should work:
^(?:(?!ABC).{3,})?XYZ
And if it also should not appear after XYZ
:
^(?:(?!ABC).{3,})?XYZ(?:.{3,}(?<!ABC))?$
Upvotes: 0
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
Reputation: 91472
is there anything wrong with
string.Contains("XYZ") && !string.contains("ABC")
Upvotes: 2