Java 中的正则表达式 re{ n, m} 元字符
子表达式/元字符“re{ n, m}”匹配前面的表达式至少出现 n 次且最多出现 m 次。
示例 1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "xyy{2,4}"; String input = "xxyyzxxyyyyxyyzxxyyzz"; 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: 1
示例 2
以下 Java 程序从用户读取名字的值,它只允许 1 到 20 个字符。
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main(String args[] ) { //Regular expression to match characters at least 1 almost 20 String regex = "[a-zA-Z]{1,20}"; Scanner sc = new Scanner(System.in); System.out.println("Enter students name:"); String name = sc.nextLine(); Pattern p = Pattern.compile(regex); Matcher m = p.matcher(name); if(m.matches()) { System.out.println("Name is appropriate"); } else { System.out.println("Name is inappropriate"); } } }
输出 1
Enter students name: Mouktika Name is appropriate
输出 2
Enter students name: ka 34 Name is inappropriate
输出 3
Enter students name: Sri Veera Venkata Satya Sai Suresh Santosh Samrat Name is in inappropriate
广告