1

I would like to know if there's any logical and operators in a regex, for example I want to do something like match a-z and A-Z but not e/E/i/I.

I tried something like

[a-zA-Z]&[^eEiI]

But it's just plain wrong, there's no such operator in any regexes.

But weirdly there's an or operator that can be used within groups like (x|y).

So I was wondering if there's any work around when there's a need to include a logical and condition in regexes.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

1 Answers1

4

You have 2 options:

1: Use negative lookahead:

(?![eEiI])[a-zA-Z]

2: Use negated character class and exclude few characters:

[a-df-hj-zA-DF-HJ-Z]

Additionally, if you are using Java as regex flavor then you can use:

[a-zA-Z&&[^eEiI]]
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • The Java flavor did the trick for me, since I was using Java. Can you point me to some regex learning resources for Java? – Amit_dash_234 Jan 23 '23 at 07:02
  • One question regarding the negative lookahead(the exp is a look behind, you may have a typo there) , lookbehind are just for looking behind, right? In a sample string like say "usefulness" here the regex should match all chars except e, but using the negative lookbehind version, wouldn't that also leave the first 'f' and second 's' since the char behind is e which would mean that the match would fail, can you elaborate more? – Amit_dash_234 Jan 23 '23 at 07:14
  • Here is Javadoc: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html – anubhava Jan 23 '23 at 07:16
  • 1
    I have indeed used negative lookahead not a look behind expression. We were looking at the next character so a lookahead. – anubhava Jan 23 '23 at 07:18