Flag này bật chế độ nhiều dòng (multiline mode).
Thông thường, metacharacter ^ và $ khớp với đầu và cuối của toàn bộ input, bất kể số dòng.
Ví dụ 1: Không dùng MULTILINE
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
public static void main(String args[]) {
String input = "2234 This is a sample text\n"
+ "1424 This second 2335 line\n"
+ "This id third 455 line\n"
+ "Welcome to Tutorialspoint\n";
Pattern pattern = Pattern.compile("^([0-9]+).*");
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
Kết quả
2234
Khi dùng flag MULTILINE trong compile(), toàn bộ chuỗi input được coi như nhiều dòng, và ^ $ khớp với đầu và cuối mỗi dòng.
Ví dụ 2: Có dùng MULTILINE
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MULTILINE_Example {
public static void main(String args[]) {
String input = "2234 This is a sample text\n"
+ "1424 This second 2335 line\n"
+ "This id third 455 line\n"
+ "Welcome to Tutorialspoint\n";
Pattern pattern = Pattern.compile("^([0-9]+).*", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(input);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}
Kết quả
2234 1424
Tóm tắt: Không flag: ^ $ khớp đầu/cuối cả chuỗi. Có MULTILINE: ^ $ khớp đầu/cuối từng dòng (ngay sau/trước \n).