Using Pattern.MULTILINE in java regex -


from api:

multiline

public static final int multiline

enables multiline mode. in multiline mode expressions ^ , $ match after or before, respectively, line terminator or end of input sequence. default these expressions match @ beginning , end of entire input sequence.

multiline mode can enabled via embedded flag expression (?m).

can make real life code example of difference of having pattern created pattern.multiline , standard settings?

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

what change using pattern.multiline?

contrived example: want match specific import line in java source file, say:

import foo.bar.baz; 

in order match line anywhere in input, multiline, easier solution use pattern.multiline along regex:

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

here ^ match right after newline , $ right before. desirable in such situation.

and:

the boundary matcher ^ default should match beginning of line , $ end of line tutorial explaines.

this untrue. default, ^ matches beginning of input, , $ matches end of 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 

Comments