ซับนิพจน์/เมตาอักขระ “( )” จัดกลุ่มนิพจน์ปกติและจดจำข้อความที่จับคู่ได้ (capturing group)
ตัวอย่างที่ 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main( String args[] ) {
String input = "Hello how are you welcome to Tutorialspoint";
String regex = "H(ell|ow)";
// คอมไพล์นิพจน์ปกติ
Pattern pattern = Pattern.compile(regex);
// ดึงออบเจ็กต์ matcher
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}ผลลัพธ์
Match found
ตัวอย่างที่ 2
ในตัวอย่างต่อไปนี้ เราพยายามจับคู่ประโยคที่มีตัวเลขอยู่
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternExample {
public static void main(String[] args) {
System.out.println("Enter input string: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// นิพจน์ปกติใช้กลุ่ม
String regex = "(?:.*)(\\d+)(.*)";
// สร้างออบเจ็กต์ pattern
Pattern pattern = Pattern.compile(regex);
// สร้างออบเจ็กต์ Matcher
Matcher matcher = pattern.matcher(input);
boolean bool = matcher.matches();
if(bool) {
System.out.println("Match found");
} else {
System.out.println("Match not found");
}
}
}ผลลัพธ์
Enter input string: This is a 5363 test string Match found