emvavra
emvavra

Reputation: 33

regex - match everything except certain strings

To verify the regex for my purposes I use the Scala console with: "REGEX".r.findFirstIn("exampleString").isDefinied

I have a lot of Strings, which I want to match with regex.
Whenever the String is exactly "foo" or "bar", I want the above to be false.

The closest I got is ^((?!foo|bar).)*$.
The problem with this is though, that everything is false once it contains either "foo" or "bar", although I would want "foof" to be true.

UPDATE:
I do need this regex for the configuration of a script. So I can't use Scala methods or change the way the regex is handled.

Upvotes: 3

Views: 2359

Answers (3)

Petr
Petr

Reputation: 63379

This pattern works ^(?!(foo|bar)$). A testing example:

import java.util.regex.Pattern;

object NotRE extends App {
  val p = Pattern.compile("^(?!(foo|bar)$)");

  val test = Seq("foo", "bar", "1foo", "foo1", "2bar", "bar2", "3bar3", "3foo3");

  print(test map ((x: String) => (x, p.matcher(x).find())));
}

Upvotes: 1

Rorick
Rorick

Reputation: 8953

Why not allow only those strings that do not match ^(foo|bar)$? If this is not an option try this regex: ^(?!^(foo|bar)$).*$.

Upvotes: 3

dhg
dhg

Reputation: 52681

How about this?

scala> def isFooOrBar(s: String) = !s.matches("""foo|bar""")
isFooOrBar: (s: String)Boolean

scala> isFooOrBar("foo")
res4: Boolean = false

scala> isFooOrBar("bar")
res5: Boolean = false

scala> isFooOrBar("foof")
res6: Boolean = true

Upvotes: 1

Related Questions