Phần biểu thức/metaký tự “\W” khớp với các ký tự không phải từ (non-word characters).
Ví dụ 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main(String args[]) {
String regex = "\\W!";
String input = "Hello 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: 1
Ví dụ 2
Ví dụ sau đọc 5 giá trị chuỗi và in ra những chuỗi chứa ký tự không phải từ.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
String regex = "\\W.*$";
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("Các chuỗi chứa ký tự không phải từ: ");
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: $hello sample test1 test2 #$&* Các chuỗi chứa ký tự không phải từ: $hello #$&*