Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 800
Kevin Lin Avatar asked Apr 01 '26 07:04

Kevin Lin


1 Answers

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.

like image 196
Wiktor Stribiżew Avatar answered Apr 03 '26 20:04

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!