Java中正則表示式re{ n}元字元
子表示式/元字元“re{ n}”與前一個表示式的 n 個出現次數完全匹配。
示例 1
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExample {
public static void main( String args[] ) {
String regex = "to{1}";
String input = "Welcome to Tutorialspoint";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
int count = 0;
while(m.find()) {
count++;
}
System.out.println("Number of matches: "+count);
}
}輸出
Number of matches: 2
示例 2
下面是 Java 程式,它從使用者讀取年齡,它只允許兩位數字。
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 = "\d{2}";
System.out.println("Enter your age:");
Scanner sc = new Scanner(System.in);
String input = sc.nextLine();
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
if(m.matches()) {
System.out.println("Age value accepted");
} else {
System.out.println("Age value not accepted");
}
}
}輸出 1
Enter your age: 25 Age value accepted
輸出 2
Enter your age: 2252 Age value not accepted
輸出 3
Enter your age: twenty Age value not accepted
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP