////匹配
使用的是String中的matches()方法
//////分割
使用的是String中的split()方法
///替换
使用的是String中的replaceAll()方法
- packagecom.xuan.demo;
- importjava.util.regex.Matcher;
- importjava.util.regex.Pattern;
- publicclassRegexDemo{
- publicstaticvoidmain(String[]args){
- System.out.println("正则表达式");
- ///匹配
- RegexFunction2();
- ///分割
- sqplitDemo();
- ///替换
- replaceAllDemo();
- //获取
- PatternDemo();
- }
- publicstaticvoidPatternDemo(){
- Stringstr="nilovming,xixi,hahaIloveYou,fanxiaoxiao,jiadashu";
- //Stringregex="[a-z]{3}";///这写法获取有问题,没有指定边界
- Stringregex="\\b[a-z]{3}\\b";//有指定边界
- //将正则封装成对象
- Patternp=Pattern.compile(regex);
- //通过正则获取匹配对象
- Matcherm=p.matcher(str);
- //m.find();///查找,找到返回true
- while(m.find()){
- System.out.println("-----:"+m.group());
- }
- publicstaticvoidreplaceAllDemo(){
- Stringstr="xixitttttthahaniniwwwwwwwwwhehe";
- ///将叠词替换成#号
- //str=str.replaceAll("(.)\\1+","#");//把连续重复的替换成#号
- str=str.replaceAll("(.)\\1+","$1");//把连续重复的替换成一个:==>xixithahaniniwhehe
- System.out.println("======>"+str);
- Stringtel="15800001111";
- ///(\\d{3})封装成组$1,(\\d{4})封装成组$2
- tel=tel.replaceAll("(\\d{3})\\d{5}(\\d{3})","$1****$2");
- System.out.println("=====>"+tel);///===>158****111
- publicstaticvoidsqplitDemo(){
- Stringstr="xiaomingwangcaixiaoqiangxiaoli";
- String[]names=str.split("\\");
- /*Stringstr="xiaoming.wangcai.xiaoqiang";
- String[]names=str.split("\\.");*/
- for(Stringname:names){
- System.out.println("----->"+name);
- publicstaticvoidRegexFunction2(){
- ///手机校验
- ///第一位只能为1,第二位:只能是3,5,8,;后面9位数只能是数字,不能出现字母
- //Stringregex="1[358][0-9]{9}";
- Stringregex="1[358]\\d{9}";//简写
- booleanb=tel.matches(regex);
- System.out.println(tel+"==>"+b);
- }