Bảng chữ cái tiếng Anh (cả hai trường hợp) và, các chữ số (0 đến 9) được coi là các ký tự từ. Bạn có thể đối sánh chúng bằng ký tự meta “\ w”.
Ví dụ 1
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String args[]) {
//Reading String from user
System.out.println("Enter a String");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
String regex = "^\\w{5}";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//Retrieving the matcher object
Matcher matcher = pattern.matcher(input);
if(matcher.find()) {
System.out.println("Match occurred");
} else {
System.out.println("Match not occurred");
}
}
} Đầu ra 1
Enter a String hello Match occurred
Đầu ra 2
Enter a String #how Match not occurred
Ví dụ 2
import java.util.Scanner;
public class RegexExample {
public static void main( String args[] ) {
//regular expression to accept word characters
String regex = "\\w*";
System.out.println("Enter input value: ");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
boolean bool = input.matches(regex);
if(bool) {
System.out.println("match occurred");
} else {
System.out.println("match not occurred");
}
}
} Đầu ra
Enter input value: *##& match not occurred