Kevin Meredith
Kevin Meredith

Reputation: 41909

Include AlphaNumeric, but Don't Match a Particular Word

How can I write a Regex for:

equals any upper-cased alphanumeric [0-9A-Z]+ one or more times, but not equal to FOO?

I've seen ^ to exclude any of the following characters, such as "exclude xyz":

scala> val blockXYZ = """[^XYZ]+""".r
blockXYZ: scala.util.matching.Regex = [^XYZ]+

scala> "XXXX".matches(blockXYZ.toString)
res26: Boolean = false

scala> "AAA".matches(blockXYZ.toString)
res27: Boolean = true

scala> "AAAX".matches(blockXYZ.toString)
res28: Boolean = false

But, I'm not sure how to not match a whole word and match on alphanumeric characters.

Upvotes: 2

Views: 71

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 31005

Additional to anubhava answer you can use another option like:

\bFOO\b|([0-9A-Z]+)

And use the capturing group to keep with the content you want

Working demo

Upvotes: 0

anubhava
anubhava

Reputation: 785266

You need to use negative lookahead in your regex:

^(?!FOO$)[0-9A-Z]+$

(?!FOO$) means don't match following pattern [0-9A-Z]+ if it is FOO followed by end of input.

Upvotes: 4

Related Questions