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

更新于: 19-11-2019

106次浏览

开启你的 职业生涯

通过完成课程取得认证

开始
广告
© . All rights reserved.