Phần biểu thức/metaký tự “.” khớp với bất kỳ ký tự đơn nào trừ ký tự xuống dòng (newline).
Ví dụ 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MatchesAll {
public static void main(String args[]) {
String regex = ".";
String input = "Hi how are you welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while (m.find()) {
count++;
}
System.out.println("Số lần khớp: " + count);
}
}
Kết quả
Số lần khớp: 40
Ví dụ 2
Chương trình Java sau chấp nhận 5 chuỗi từ người dùng và in ra các từ 4 ký tự kết thúc bằng e.
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 = "...e";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập 5 chuỗi đầu vào: ");
String input[] = new String[5];
for (int i = 0; i < 5; i++) {
input[i] = sc.nextLine();
}
// Tạo đối tượng Pattern
Pattern p = Pattern.compile(regex);
System.out.println("Từ 4 chữ cái kết thúc bằng e: ");
for (int i = 0; i < 5; i++) {
// Tạo đối tượng Matcher
Matcher m = p.matcher(input[i]);
if (m.matches()) {
System.out.println(m.group());
}
}
}
}
Kết quả
Nhập 5 chuỗi đầu vào: hive sample wife life naive Từ 4 chữ cái kết thúc bằng e: hive wife life