Field COMMENTS ของคลาส Pattern อนุญาตให้มี whitespace และ comments ใน pattern เมื่อคุณใช้เป็น flag value ในเมธอด compile() whitespace และ comments ที่ขึ้นต้นด้วย # จะถูกละเว้นใน pattern ที่กำหนด
ตัวอย่างที่ 1: ใช้ COMMENTS กับ regex ที่มี comment
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("Enter input data: ");
String input = sc.nextLine();
// Regular expression to find digits
String regex = "\\d #ignore this comment\n";
// คอมไพล์ regular expression
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
// ดึง Matcher object
Matcher matcher = pattern.matcher(input);
int count = 0;
String result = "";
while (matcher.find()) {
count++;
result = result + matcher.group();
}
System.out.println("Number of digits in the given text: " + count);
}
}
Output
Enter input data: sample1 text2 with3 numbers4 in5 between6 Number of digits in the given text: 6
ตัวอย่างที่ 2: ใช้ COMMENTS เขียน regex วันที่อ่านง่าย
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("Enter your name: ");
String name = sc.nextLine();
System.out.println("Enter your Date of birth: ");
String dob = sc.nextLine();
// Regular expression to accept date in MM-DD-YYY format
String regex = "^(1[0-2]|0[1-9])/ \n" + "# For Month\n" + "(3[01]|[12][0-9]|0[1-9])/ \n" + "# For Date\n" + "[0-9]{4}$ # For Year";
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
// สร้าง Matcher object
Matcher matcher = pattern.matcher(dob);
boolean result = matcher.matches();
if (result) {
System.out.println("Given date of birth is valid");
} else {
System.out.println("Given date of birth is not valid");
}
}
}
Output
Enter your name: Krishna Enter your Date of birth: 09/26/1989 Given date of birth is valid