如何使用 Java RegEx 匹配表达式 n 次?
Java 提供的贪心量词允许你匹配表达式的多次出现。其中:
Exp{n} 驱使表达式 exp 确切出现 n 次。
Exp{n,} 驱使表达式 exp 至少出现 n 次。
Exp{n, m} 驱使表达式 exp 至少出现 n 次,至多出现 m 次。
示例 1
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 accept 5 letter word String regex = "\w{5}"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.find()) { System.out.println(input[i]+": accepted"); } else { System.out.println(input[i]+": not accepted"); } } } }
输出
Enter 5 input strings: rama raja raghu megha malya rama: not accepted raja: not accepted raghu: accepted megha: accepted malya: accepted
示例 2
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 a string of non-word with length 2 to 6 String regex = "\W{2,6}"; Scanner sc = new Scanner(System.in); System.out.println("Enter 5 input strings: "); String input[] = new String[5]; for (int i=0; i<5; i++) { input[i] = sc.nextLine(); } //Creating a Pattern object Pattern p = Pattern.compile(regex); for(int i=0; i<5;i++) { //Creating a Matcher object Matcher m = p.matcher(input[i]); if(m.find()) { System.out.println(input[i]+" matched"); } } } }
输出 1
Enter 5 input strings: hello how are you #$#% # #$@%%#&#& sample text #$#% matched #$@%%#&#& matched
示例 3
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 = "[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"); } } }
输出
Enter students name: Mouktika Name is appropriate
广告