解释Java正则表达式中的量词
如果要在构造正则表达式时指定出现次数,则可以使用量词。下表列出了Java正则表达式支持的量词-
示例
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main( String args[] ) { String regex = "[0-9]{3,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(); } //创建一个Pattern对象 Pattern p = Pattern.compile(regex); System.out.println("Matched values: "); for(int i=0; i<5;i++) { //创建一个Matcher对象 Matcher m = p.matcher(input[i]); if(m.matches()) { System.out.println(m.group()+": accepted "); } } } }
输出结果
Enter 5 input strings: 12 154 4587 478365 4578952 Matched values: 154: accepted 4587: accepted 478365: accepted