6

From this API:

MULTILINE

public static final int 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).

Can anybody make a real life code example of the difference of having a Pattern created with Pattern.MULTILINE and with standard settings?

The boundary matcher ^ as default should match the beginning of the line and $ the end of the line as this tutorial explaines.

What does it change by using the Pattern.MULTILINE?

1 Answer 1

9

Contrived example: you want to match a specific import line in a Java source file, say:

import foo.bar.Baz;

In order to match that line anywhere in the input, which is multiline, the easier solution is to use Pattern.MULTILINE along with this regex:

^\s*import\s+foo\.bar\.Baz\s*;\s*$

Here the ^ will match right after a newline and the $ right before. Which is desirable in such a situation.

And:

The boundary matcher ^ as default should match the beginning of the line and $ the end of the line as this tutorial explaines.

this is untrue. By default, ^ matches the beginning of the input, and $ matches the end of the input.

Illustration:

public static void main(final String... args)
{
    final Pattern p1 = Pattern.compile("^dog$");
    final Pattern p2 = Pattern.compile("^dog$", Pattern.MULTILINE);

    final String input = "cat\ndog\nTasmanian devil";

    System.out.println(p1.matcher(input).find());
    System.out.println(p2.matcher(input).find());
}

This outputs:

false
true
Sign up to request clarification or add additional context in comments.

3 Comments

So the oracle tutorial I linked (in the latter bit you quoted) is wrong?
What is the difference between \A and ^ then?
The difference is that \A will always match the beginning of input, even with Pattern.MULTILINE. In the second regex above, if you replace ^ by \A, then the second printout will be false.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.