เมตาอักขระ “.” ในนิพจน์ปกติ Java จับคู่กับตัวอักษรใดๆ (ตัวเดียว) อาจเป็นตัวอักษร ตัวเลข หรือ อักขระพิเศษก็ได้
ตัวอย่างที่ 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
// อ่านสตริงจากผู้ใช้
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
// นิพจน์ปกติจับคู่ตัวอักษรใดๆ
String regex = ".";
// คอมไพล์นิพจน์ปกติ
Pattern pattern = Pattern.compile(regex);
// ดึงออบเจ็กต์ matcher
Matcher matcher = pattern.matcher(input);
int count = 0;
while(matcher.find()) {
count++;
}
System.out.println("Given string contains " + count + " characters.");
}
}ผลลัพธ์
Enter a String hello how are you welcome to tutorialspoint Given string contains 42 characters.
คุณสามารถจับคู่ตัวอักษร 3 ตัวระหว่าง a และ b โดยใช้นิพจน์ปกติดังนี้:
a...b
เช่นเดียวกัน นิพจน์ “.*” จับคู่ตัวอักษรจำนวน n ตัว
ตัวอย่างที่ 2
โปรแกรม Java ต่อไปนี้อ่าน 5 สตริงจากผู้ใช้ และยอมรับสตริงที่เริ่มด้วย b จบด้วย a และมีตัวอักษรจำนวนเท่าไรก็ได้ระหว่างกลาง
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "^b.*a$";
Scanner sc = new Scanner(System.in);
System.out.println("Enter 5 input strings: ");
String input[] = new String[5];
for (int i=0; i<5; i++) {
input[i] = sc.nextLine();
}
// สร้างออบเจ็กต์ Pattern
Pattern p = Pattern.compile(regex);
for(int i=0; i<5;i++) {
// สร้างออบเจ็กต์ Matcher
Matcher m = p.matcher(input[i]);
if(m.find()) {
System.out.println(input[i] + ": accepted");
} else {
System.out.println(input[i] + ": not accepted");
}
}
}
}ผลลัพธ์
Enter 5 input strings: barbara boolean baroda ram raju barbara: accepted boolean: not accepted baroda: accepted ram: not accepted raju: not accepted