Trường COMMENTS của lớp Pattern cho phép khoảng trắng và comment trong pattern. Khi dùng flag này trong compile(), khoảng trắng và comment bắt đầu bằng # bị bỏ qua trong pattern.
Ví dụ 1: Regex có comment và khoảng trắng
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập dữ liệu đầu vào: ");
String input = sc.nextLine();
// Regex: \d # comment này bị bỏ qua
String regex = "\\d #ignore this comment\n";
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
Matcher matcher = pattern.matcher(input);
int count = 0;
String result = "";
while (matcher.find()) {
count++;
result = result + matcher.group();
}
System.out.println("Số chữ số trong văn bản: " + count);
}
}
Kết quả
Nhập dữ liệu đầu vào: sample1 text2 with3 numbers4 in5 between6 Số chữ số trong văn bản: 6
Ví dụ 2: Regex đa dòng với comment cho ngày tháng
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Nhập tên: ");
String name = sc.nextLine();
System.out.println("Nhập ngày sinh (MM/DD/YYYY): ");
String dob = sc.nextLine();
// Regex có comment, khoảng trắng được bỏ qua
String regex = "^(1[0-2]|0[1-9])/ " // For Month\n"
+ "(3[01]|[12][0-9]|0[1-9])/ " // For Date\n"
+ "[0-9]{4}$ # For Year";
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
Matcher matcher = pattern.matcher(dob);
boolean result = matcher.matches();
if (result) {
System.out.println("Ngày sinh hợp lệ");
} else {
System.out.println("Ngày sinh không hợp lệ");
}
}
}
Kết quả
Nhập tên: Krishna Nhập ngày sinh: 09/26/1989 Ngày sinh hợp lệ
Lợi ích: Viết regex dễ đọc, có comment, thụt lề, không lo khoảng trắng thừa bị coi là literal space.