默认情况下,当我们使用“.”时表达式中,我们将匹配输入字符串中的每个字符,直到遇到新行字符。
使用此标志,匹配也将包括行终止符。我们将通过以下示例更好地理解。这些例子将略有不同。由于我们感兴趣的是针对匹配的字符串进行断言,因此我们将使用matcher的group方法来返回之前的匹配。
首先,我们将看到默认行为:
@Test public void givenRegexWithLineTerminator_whenMatchFails_thenCorrect() { Pattern pattern = Pattern.compile("(.*)"); Matcher matcher = pattern.matcher( "this is a text" + System.getProperty("line.separator") + " continued on another line"); matcher.find(); assertEquals("this is a text", matcher.group(1)); }
正如我们所看到的,只有行终止符之前输入的第一部分匹配。
现在在dotall模式下,包括行终止符在内的整个文本都将匹配:
@Test public void givenRegexWithLineTerminator_whenMatchesWithDotall_thenCorrect() { Pattern pattern = Pattern.compile("(.*)", Pattern.DOTALL); Matcher matcher = pattern.matcher( "this is a text" + System.getProperty("line.separator") + " continued on another line"); matcher.find(); assertEquals( "this is a text" + System.getProperty("line.separator") + " continued on another line", matcher.group(1)); }
我们还可以使用嵌入的标志表达式来启用dotall模式: