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 Nhooo";
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("输入您的年龄:");
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
输入您的年龄: 25 Age value accepted
输出2
输入您的年龄: 2252 Age value not accepted
输出3
输入您的年龄: twenty Age value not accepted