最新下载
热门教程
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
java 正则表达式函数Pattern.matcher()的使用方法
时间:2011-05-21 编辑:简简单单 来源:一聚教程网
public Pattern.matcher(CharSequence input) 得到一个要比较字符序列是input的比较器(matcher)
public static boolean Pattern.matches(String regex,CharSequence input)
在字符序列input查找正则表达式regex对应的pattern,
等同与Pattern.compile(regex).matcher(input).matches();
如果regex要使用多次,请使用下面的形式,可以省去编译regex的时间
Pattern partn = Pattern.compile(regex);
partn.matcher(input).matches();
match()的参数一般为正则表达式,现在两个正则表达式,可以试用
正则表达式一:可以适用任何形式的字符串,
其中LikeType是要匹配的字符串,patten是生成的正则表达式,sourceStr是已有字符串,判断sourceStr是否满足LikeType的正则表达式
public static void main(String[] args) {
// TODO Auto-generated method stub
String likeType = "23";
String pattern = "[a-zA-Z0-9]*[" + likeType + "]{1}[a-zA-Z0-9]*";
String sourceStr = "adfjaslfj23ldfalsf";
System.out.println(sourceStr.matches(likeType));
}
正则表达式二:固定位置的字符串匹配,理解同上,只是正则表达式的不同
public static void main(String[] args) {
// TODO Auto-generated method stub
String likeType = "%%%23%%%*";
String sourceStr = "423236664";
likeType = likeType.replaceAll("%", "\d").replaceAll("*", "\d*");
System.out.println(likeType);
System.out.println(sourceStr.matches(likeType));
}
电话号正则表达式
public class Main {
public static void main(String args[]) {
String phone = "(111)-111-1111";
String phoneNumberPattern = "(d-)?(d{3}-)?d{3}-d{4}";
System.out.println(phone.matches(phoneNumberPattern));
}
}
match的方法比较简单,但绝对实用,所以要掌握用法,正则表达式的写法尤其重要
邮箱号
public class Main {
public static void main(String[] a) {
String zip = "1234-123";
String zipCodePattern = "d{5}(-d{4})?";
boolean retval = zip.matches(zipCodePattern);}
}日期合法性正则
public class Main {
public static void main(String[] argv) throws Exception {boolean retval = false;
String date = "12/12/1212";
String datePattern = "d{1,2}-d{1,2}-d{4}";
retval = date.matches(datePattern);}
}
-
上一个: java数据类型之间转换应用方法
-
下一个: java lock讲解与用法
相关文章
- email正则表达式函数 09-02
- SpringBoot测试配置属性与web启动环境解析 10-24
- vue中将el-switch值true、false改为number类型的1和0解析 10-24
- Vue中的路由配置项meta使用解读 10-24
- SpringBoot自定义bean绑定解析 10-24
- SpringBoot常用计量与bean属性校验和进制数据转换规则解析 10-24