以下1,2等效:
1.Pattern.matches(regex, input); //编译给定正则表达式并尝试将给定输入与其匹配。
2.Pattern.compile(regex).matcher(input).matches() //用于多次使用一种模式
步骤详解:
2-1: Pattern p = Pattern.compile(regex); //将正则表达式编译到Pattern模式中
2-2: Matcher m = p.matcher(input); //创建匹配器(给定输入与此模式的)
2-3: m.matches(); //看是否能匹配,匹配就返回true
Example:
String regex = "1[3578]\\d{9}";
String s = "我的手机是18510086620,我曾用过13987654321,还用过17812345678";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(s);
while(m.find())
System.out.println(m.group()); |
|