Kevin Lin
Kevin Lin

Reputation: 681

String.contains finds a substring but not Pattern.matches?

In one of my try/catch blocks, I catch an exception e, and this:

e.toString().contains("this is a substring") returns true

while

Pattern.matches(".*this is a substring.*", e.toString()) returns false

Why does this happen? Including the .* as the prefix and suffix for the regex pattern should essentially make these two functions do the same thing right?

Upvotes: 3

Views: 675

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

If your input string contains newline symbol(s), .* is not enough in .matches() that requires a full string match.

Thus, you need a DOTALL modifier:

Pattern.matches("(?s).*this is a substring.*", e.toString())
                 ^^^^ 

See the Java regex reference:

In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators.

Dotall mode can also be enabled via the embedded flag expression (?s). (The s is a mnemonic for "single-line" mode, which is what this is called in Perl.)

NOTE: if you need to check the presence of a literal substring inside a longer string, a .contains() method should work faster. Or, if you need a case insensitive contains, you may also check StringUtils.containsIgnoreCase.

Upvotes: 6

Related Questions