1

Any idea why this Java test case fails?

@Test
public void newlineParse() throws Exception {
    Pattern pat = Pattern.compile("a.*b", Pattern.MULTILINE);
    assertTrue(pat.matcher("a\nb").find());
}
Magnus
  • 10,736
  • 5
  • 44
  • 57
  • 1
    Maybe because `.` matches any character except line terminators. – jrook Oct 17 '18 at 23:13
  • 2
    I thought it was `DOTALL` not `MULTILINE`, but it has been a while. – KevinO Oct 17 '18 at 23:13
  • 2
    *The regular expression . matches any character except a line terminator unless the DOTALL flag is specified.* from [the docs](https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html#lt) – jrook Oct 17 '18 at 23:15
  • 1
    Yes. MULTILINE modifies the behavior of `^` and `$` – Stephen C Oct 17 '18 at 23:18
  • You people really need to stop reading the documentation. How the heck would we have any questions at all here on SO if everyone suddenly started reading the docs? – markspace Oct 17 '18 at 23:39

1 Answers1

6

I believe the issue is that the Pattern.MULTILNE is incorrect. For the particular example, it should be Pattern.DOTALL (or embed the ?s in the expression).

MULTILINE:

Enables multiline mode.
In multiline mode the expressions ^ and $ match just after or just before, respectively, a line terminator or the end of the input sequence. By default these expressions only match at the beginning and the end of the entire input sequence.
Multiline mode can also be enabled via the embedded flag expression (?m).

DOTALL:

In dotall mode, the expression . matches any character, including a line terminator. By default this expression does not match line terminators.

A working example using DOTALL

KevinO
  • 4,303
  • 4
  • 27
  • 36