Metacharacter . (dot)
. khớp bất kỳ ký tự đơn nào (trừ newline mặc định).
Quy trình
- Compile regex
. - Tạo Matcher
- Vòng lặp
find(), ingroup()cho mỗi match
Ví dụ
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 = ".";
Scanner sc = new Scanner(System.in);
System.out.println("Nhập chuỗi: ");
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
while (m.find()) {
System.out.println(m.group());
}
}
}
Kết quả
Nhập chuỗi: This is a sample text
T
h
i
s
i
s
a
s
a
m
p
l
e
t
e
x
t
Cách đơn giản hơn (không cần regex)
// Duyệt char array
for (char c : input.toCharArray()) {
System.out.println(c);
}
// Hoặc Java 8+
input.chars().forEach(c -> System.out.println((char)c));
Lưu ý
- Dùng regex
.cho demo/giáo dục. Thực tế dùngtoCharArray()hiệu quả hơn. - Để khớp cả newline:
Pattern.DOTALLflag hoặc(?s).