Dónal
Dónal

Reputation: 187499

Java Regular Expression

I need to define a (Java) regex that will match any string that does NOT contain any of these

Is it possible to express this as a single regex? I know it would be more readable to use 3 separate regexs, but I'd like to do it in one if possible.

Thanks, Don

Upvotes: 1

Views: 184

Answers (2)

Paul Wagland
Paul Wagland

Reputation: 29096

Try the following:

final private static Pattern p = Pattern.compile(".*\\b(?:foos?|bars?|bazs?)\\b.*");
public boolean isGoodString(String stringToTest) {
  return !p.matcher(stringToTest).matches();
}

Upvotes: 6

Rubens Farias
Rubens Farias

Reputation: 57936

Here you go:

^((?!\bfoos?|bars?|bazs?\b).)*$

Upvotes: 2

Related Questions