简体   繁体   English

String.contains找到一个子字符串但不是Pattern.matches?

[英]String.contains finds a substring but not Pattern.matches?

In one of my try/catch blocks, I catch an exception e , and this: 在我的一个try / catch块中,我捕获了一个异常e ,这个:

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

while

Pattern.matches(".*this is a substring.*", e.toString()) returns false Pattern.matches(".*this is a substring.*", e.toString())返回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. 如果输入字符串包含换行符号,则.matches()中的.*是不够的,需要完整的字符串匹配。

Thus, you need a DOTALL modifier: 因此,您需要一个DOTALL修饰符:

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

See the Java regex reference : 请参阅Java正则表达式参考

In dotall mode, the expression . 在dotall模式中,表达式. 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) . 也可以通过嵌入式标志表达式(?s)启用Dotall模式。 (The s is a mnemonic for "single-line" mode, which is what this is called in Perl.) s是“单行”模式的助记符,这是在Perl中调用的。)

NOTE : if you need to check the presence of a literal substring inside a longer string, a .contains() method should work faster. 注意 :如果需要检查较长字符串中是否存在文字子字符串,则.contains()方法应该更快。 Or, if you need a case insensitive contains , you may also check StringUtils.containsIgnoreCase . 或者,如果你需要区分大小写的contains ,你也可以检查StringUtils.containsIgnoreCase

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM