如何使用 Java RegEx 匹配單詞字元?
英文和數字(0 至 9)都屬於單詞字元。可以使用元字元“\w”來匹配這些字元。
示例 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");
}
}
}輸出 1
Enter a String hello Match occurred
輸出 2
Enter a String #how Match not occurred
示例 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");
}
}
}輸出
Enter input value: *##& match not occurred
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP