Regex: Maching only if xzy is NOT in string

Hello! This is probably a really easy question, but I want to match a string if:

  1. ABC is in the string
    Then some characters…
    and
  2. XYZ and JKL are NOT in the string

Another way to put it would be… the string can end in anything but XYZ and JKL.

This is how I match if abc is in the string AND XYZ or JKL is in the string. How do I do the opposite for XYZ and JKL?

m/ABC.*((XYZ)|(JKL))$/i

Edit: I am not using any scripting language, so any logic outside of the regex is out of the question. To the best of my knowledge, this command-line tool accepts Perl-like regex.

Well, I fixed it myself.

ABC(?!(.*XYZ.*)|(.*JKL.*)).*$

Thanks for the help, ScallioXTX!

You’re most welcome Clete :slight_smile:

Hmm. I’m still having some trouble with this.

m/ABC.*([COLOR=blue]?![/COLOR](XYZ)|(JKL))$/i

Example string:

alphabetsoup.ABC.DEF.MORETEXT.XYZ

This seems to match. It shouldn’t. I think the problem is that .* is just matching the rest of the line.

If I make the “.” in the regex ungreedy “.*?” then it only matches up to “ABC.” and will never match the rest of the line.

And this is why I love regular expressions.

Thanks for your help, that’s exactly what I’m looking for. I have never used lookahead or lookbehind before. I’ll have to study up…

You should use negative lookahead (if your tools supports it of course):


m/ABC.*([COLOR="Blue"]?![/COLOR](XYZ)|(JKL))$/i

:slight_smile: