您的位置:首页 > 编程语言 > Java开发

Java正则表达式整理的工具类

2016-07-17 10:58 429 查看
1,确定的开头,确定的结尾,中间字符任意匹配(开头结尾没有传空):

//first为开头的字母(空字符,单个或多个),last为结尾的字母(空字符,单个或多个),match为要匹配的字母
public static boolean firstOrLastMatch(String first,String last,String match){
Pattern p=null;
Matcher m=null;
boolean b=false;
p=Pattern.compile(first+".*"+last);
m=p.matcher(match);
b=m.matches();
return b;
}


知识点:"."表示匹配任意字符,"*"表示重复任意次。

2,是否是固定长度的一串数字:

//length表示指定的长度是多少,number表示待匹配的数字串
public static boolean isFixedLengthNumber(int length,String number){
Pattern p=null;
Matcher m=null;
boolean b=false;
p=Pattern.compile("\\d{"+length+"}");
m=p.matcher(number);
b=m.matches();
return b;
}


知识点:"\d"表示匹配数字,"{n}"表示重复n次。

运用实例:匹配手机号码,匹配身份证

3,是否是固定长度并且特定位固定的一串数字:

//length表示固定数字后面指定的长度是多少,fixed表示要固定的数字,number表示待匹配的数字串,仅限开头为固定的数字
public static boolean isFixedLengthAndMatchNumber(int length,String fixed,String number){
Pattern p=null;
Matcher m=null;
boolean b=false;
p=Pattern.compile("["+fixed+"]+\\d{"+length+"}");
m=p.matcher(number);
b=m.matches();
return b;
}


知识点:"[]"表示匹配方括号内的一个字符,若要固定多个特定的字符请自己重写。别忘记中间的加号

运用实例:匹配手机号码,匹配身份证。

4,邮箱验证

//email表示传入的邮箱
public static boolean emailMatch(String email){
Pattern p=null;
Matcher m=null;
boolean b=false;
//[a-zA-Z0-9]{1,}:必须为字母或数字,至少一个
//[@]:必须有个@
//[a-z0-9]{1,}:必须为小写字母或数字,至少一个
//[.]:必须有个.
p=Pattern.compile("[a-zA-Z0-9]{1,}[@][a-z0-9]{1,}[.][a-z]{1,}");
m=p.matcher(email);
b=m.matches();
return b;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: