40

I have two buttons on form, one of the buttons contain currency code (EUR, USD, GBP,CHF,..) and another one - trade direction (BUY or SELL). And some utility recognize buttons by it's text. To recognize button with currencies, I use Regular expression ":[A-Z]{3}", but it don't work properly when second button contain text "BUY" (regex description returns more than one object).

Question: how can I write pattern for Regular expression, which means: match only when text contain three upper letters, but not text "BUY"?

Thanks!

vmg
  • 9,920
  • 13
  • 61
  • 90

2 Answers2

72
^(?!BUY)[A-Z]{3}$

(?!BUY) is negative lookahead that would fail if it matches the regex BUY

Community
  • 1
  • 1
Amarghosh
  • 58,710
  • 11
  • 92
  • 121
16

You can use a negative look-behind assertion to verify that the text just matched does not equal BUY.

[A-Z]{3}(?<!BUY)
Daniel Brückner
  • 59,031
  • 16
  • 99
  • 143
  • 4
    the look ahead version is more widely supported in different regex implementations, and has better performance (I think). – Jens Jul 07 '10 at 13:16
  • this worked for me in a (simulation) of java8 regex, while the accepted answer didn't – ycomp Nov 05 '17 at 05:19