Today must have been the first time in a long while that I wanted to match regular expressions across multiple lines. At least long enough that I forgot the following:
By default the dot in regular expressions does not include newlines.
(At least not in many languages, my example being Java.)
If you want the dot to match newlines, you can enable this using (?s)
in your regular expression.
Let’s look at the following code to see it in action:
private String input = "START\nline1\nline2\nline3\nEND";
private String regex = "START\n(.*)END";
@Test
public void byDefaultDotDoesNotMatchNewline() {
assertFalse(input.matches(regex));
}
@Test
public void butWeCanEnableIt() {
assertTrue(input.matches("(?s)"+regex));
}
I think I will remember that now. Enjoy.