在java中提供了正则表达式的jar包,正则表达式不仅仅局限于一种语言,单每种语言有细微的差别,正则表达式通过编辑文本模式用于搜索,编辑或处理文本。
使用正则表达式主要使用java.util.regex包下的类:Pattern,Mathcer,PatternSyntaxException。
【String中正则表达式方法】
在String类中同样提供了几个特殊的方法:
boolean matches(String regex):判断字符串是否满足指定的正则表达式。
String replaceAll(String regex,String replacement):将字符串中所有匹配的regex的字串替换成replacement。
String replaceFirst(String regex,String replacement):将字符串中第一个满足regex的子串替换成replacement。
String[] split(String regex):以regex作为分隔符,将字符串分割成多个子串。
【正则表达式语法】
通俗来讲,创建正则表达式最主要的是创建匹配字符串的模板,匹配一批字符串。它需要我们注意正则表达式支持的合法字符,特殊字符,通配符,方括号表达式。
1. 合法字符:
2. 特殊字符:
3. 通配符:
4. 方括号表达式:
5. 边界匹配符:
【正则表达式应用举例】
正则表达式举例使用:
1. pattern对象的简单使用
Pattern p=pattern.compile("a*b"); //将字符串编程成pattern对象
Mather m=p.matcher("aaaaab"); //使用pattern对象创建matcher对象
boolean b=ma.matches(); //true
2. 使用find()和group()方法找到特定电话号码
String str="我想求购一本《疯狂java》讲义,清联系我1445224556,交朋友电话是:15369657805";
Matcher m=Pattern.compile("((13\\d)|(15\\d))").matcher(str);//用于抓取13x和18x开头的字符串
while(m.find()){
System.out.println(m.group()+"/");
}
3. 通过start()和end()返回匹配子串在原来字符串的起始和终止位置。
String regStr="Java is so easy!";
Mather m=Pattern.compile("\w+").matcher(regStr);
while(m.find()){
System.out.println(m.group()+"子串起始位置是:"+m.start()+",结束位置是:"+m.end());
}
4 . 匹配邮箱
String[] mails={"xianggang@163.com","aomeng@gmail.com","Ligang@re.org"};
String mailRegex="//w{3,20}@\\w+\\.(com|org|cn|net|gov)"
Pattern mailPattern= Pattern.compile(mailRegex);
Matcher matcher=null;
for(String mail:mails){
if(matcher==null){
matcher=mailPattern.matcher(mail);
}else{
//reset()方法将Mather对象应用于新的字符串
matcher.reset(mail);
}
//matches方法要求字符串与Pattern完全匹配才返回true
//lookingAt()要求字符串以Pattern开头即可返回true
String result=mail+(mathcer.matches()?"是":"不是"+"一个有效的邮件地址");
System.out.println(result);
}
正则表达式的应用方便了我们提取字符串的操作,我们可以利用它截取文本,修改文本内容,修改文本样式等。