A regular expression for matching eggs or bacon or cheese is:
(eggs|bacon|cheese)
You need to detect when lines don't match, so you can negate the condition something like this:
if (!line.matches("(eggs|bacon|cheese)") {
// Do something
}
This matches the entire line. If you want to tell whether the line contains any of those words, you would need to match differently—either using .*
to match the rest of the line, or using Pattern
and Matcher
.
I would use: \b
to mark word boundaries, to ensure you only match cheese
and don't match cheesecake
.
Pattern pattern = Pattern.compile("\\b(eggs|bacon|cheese)\\b");
Matcher matcher = pattern.matcher(line);
if (!matcher.find()) {
// Do something
}
Alternatively:
if (!line.matches(".*\\b(eggs|bacon|cheese)\\b.*")) {
// Do something
}
You have to double up the backslashes to escape them inside a String.