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?
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). (Thesis 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With