在写代码过程中,常常遇见需要使用正则表达式的情况下,如对爬取的网页结果进行提取,对字符串进行整理等场景。在实际使用中,经常是用了就查,查完就忘的状态,所以这里想对一些常用正则表达式进行一个整理,方便以后使用。
- (?=[-+])
/**
exp="3+6-4";
token=["3","+6","-4"];
*/
String[] token=exp.split("(?=[-+])");//exp=3+6-4
2 . 判断身份证:要么是15位,要么是18位,最后一位可以为字母,并写程序提出其中的年月日。
/**
*这是一道面试题
*输出结果:年:1987月:12日:09
*
*/
String id="130681198712092019";
//首先准备判断是否满足身份证要求的正则表达式
String regex="(\\d{14})\\w|\\d{17}\\w";
Pattern regular=Pattern.compile(regex);
Matcher matcher=regular.matcher(id);
matcher.matches();//返回boolean类型,判断是否满足要求。
//提取年月日
Pattern birthDayRegularPattern=Pattern.compile("(\\d{6})(\\d{8})(.*)");
Matcher matcher1=birthDayRegularPattern.matcher(id);
if(matcher1.matches()){
Pattern YearMonthDayRegular=Pattern.compile("(\\d{4})(\\d{2})(\\d{2})");
Matcher matcher2=YearMonthDayRegular.matcher(matcher1.group(2));
if(matcher2.matches()){
StringBuilder sb=new StringBuilder();
sb.append("年:"+matcher2.group(1));
sb.append("月:"+matcher2.group(2));
sb.append("日:"+matcher2.group(3));
}
}
}
3 . 只能输入至少n个数字
/**
*输出结果:满足至少7个数字的条件
*
*/
String s="1236789012";
int least=7;
Pattern pattern=Pattern.compile("\\d{"+least+",}");
Matcher matcher=pattern.matcher(s);
if(matcher.matches()){
System.out.println("满足至少"+least+"的条件");
}else{
System.out.println("不满足至少"+least+"的条件");
}
4 . 只能输入n个字符
/**
*注意这里表达式也可以是"^.{5}$"
*java中\\用于转移字符,如\\d,\\w(不同语言语法略微不同撒)
*/
Pattern pattern=Pattern.compile(".{5}");
Matcher matcher=pattern.matcher(s);
5 . 只能输入英文字母
/**
*.表示匹配任意字符
**表示匹配0-n个字符
*+表示匹配1-n个字符
*/
Pattern pattern=Pattern.compile(".[A-Za-z]+");
Matcher matcher=pattern.matcher(s);
6 . 只能输入英文字符/数字/下划线
这里的知识点为:\\w
7 . 验证是否为汉字
Pattern pattern=Pattern.compile("[\u4e00-\u9fa5]{0,}");
Matcher matcher=pattern.matcher(s);
8 . 验证手机号(包含159,不包含小灵通)
/**
*这里主要的知识点为:{}用来表示前面内容的数量
*
*/
Pattern pattern=Pattern.compile("13[0-9]{1}[0-9]{8}|15[9]{1}[0-9]{8} ");
Matcher matcher=pattern.matcher(s);