正则表达式

来源:互联网 发布:淘宝印度代购药品被骗 编辑:程序博客网 时间:2024/05/19 14:36


正则表达式


          正则表达式:符合一定规则的表达式;
          作用:用于专门操作字符串;
          特点:用于一些特定的符号来表示一些代码操作,这样简化书写,所以学习正则表达式就是学习一些特殊符号的使用;
          好处:可以简化对字符串的复杂操作;
          弊端:符号定义越多,正则越长,阅读性越差;


示例:
/**  正则表达式。**  正则表达式用于操作字符串数据。*  通过一些特定的符号来体现的。*  所以我们为了掌握正则表达式,必须要学习一些符号。**  虽然简化了,但是阅读性差。*/public class RegexDemo{  <span style="white-space:pre"></span>public static void main(String[] args){  <span style="white-space:pre"></span>String qq = "123456701";  <span style="white-space:pre"></span>//checkQQ(qq);  <span style="white-space:pre"></span>// 正则表达式。  <span style="white-space:pre"></span>String regex = "[1-9][0-9]{4,14}";  <span style="white-space:pre"></span>boolean b = qq.matches(regex);  <span style="white-space:pre"></span>System.out.println(qq + ":" + b);  <span style="white-space:pre"></span>}  /*  *  需求:定义一个功能对 QQ 号进行校验。  *  需求:长度 5~15 ,只能是数字, 0 不能开头。  */  <span style="white-space:pre"></span>public static void checkQQ(String qq){   <span style="white-space:pre"></span>int len = qq.length();  <span style="white-space:pre"></span>if(len >= 5 && len <= 15){  <span style="white-space:pre"></span>if(!qq.startsWith("0")){  <span style="white-space:pre"></span>try{  <span style="white-space:pre"></span>long l = Long.parseLong(qq);  <span style="white-space:pre"></span>System.out.println(l + ": 正确 ");  <span style="white-space:pre"></span>   }catch(NumberFormatException e){  <span style="white-space:pre"></span>System.out.println(qq + ": 含有非法字符 ");  <span style="white-space:pre"></span>   }  <span style="white-space:pre"></span>}else{  <span style="white-space:pre"></span>System.out.println(qq + ": 不能 0 开头 ");  <span style="white-space:pre"></span>}  <span style="white-space:pre"></span>}else{  <span style="white-space:pre"></span>System.out.println(qq + ": 长度错误 ");  <span style="white-space:pre"></span>}  <span style="white-space:pre"></span>}  }



正则表达式常用构造摘要
         
         字符类
                 [abc] a、b 或 c(简单类)
                 [^abc] 任何字符,除了 a、b 或 c(否定)
                 [a-zA-Z] a 到 z 或 A 到 Z,两头的字母包括在内(范围)
        预定义字符类
.                任何字符(与行结束符可能匹配也可能不匹配)
                 \d 数字:[0-9]
                 \D 非数字: [^0-9]
                 \s 空白字符:[ \t\n\x0B\f\r]
                 \S 非空白字符:[^\s]
                 \w 单词字符:[a-zA-Z_0-9]
                 \W 非单词字符:[^\w]
        Greedy 数量词
                 X? X,一次或一次也没有
                 X* X,零次或多次
                 X+ X,一次或多次
                 X{n} X,恰好 n 次
                 X{n,} X,至少 n 次
                 X{n,m} X,至少 n 次,但是不超过 m 次
         边界匹配器
                 ^ 行的开头
                 $ 行的结尾
                 \b 单词边界
                 \B 非单词边界
                 \A 输入的开头
                 \G 上一个匹配的结尾
                 \Z 输入的结尾,仅用于最后的结束符(如果有的话)
                 \z 输入的结尾

示例:
public class RegexDemo{  <span style="white-space:pre"></span>public static void main(String[] args){   <span style="white-space:pre"></span>String str = "aoob";<span style="white-space:pre"></span>String reg = "ao?b";  <span style="white-space:pre"></span>boolean b = str.matches(reg);  <span style="white-space:pre"></span>System.out.println(str + ":" + b);  <span style="white-space:pre"></span>reg = "ao+b";  <span style="white-space:pre"></span>b = str.matches(reg);  <span style="white-space:pre"></span>System.out.println(str + ":" + b);  <span style="white-space:pre"></span>str = "ab"; <span style="white-space:pre"></span>reg = "ao+b";  <span style="white-space:pre"></span>b = str.matches(reg);  <span style="white-space:pre"></span>System.out.println(str + ":" + b);  <span style="white-space:pre"></span>str = "ab";  <span style="white-space:pre"></span>reg = "ao*b";  <span style="white-space:pre"></span>b = str.matches(reg);  <span style="white-space:pre"></span>System.out.println(str + ":" + b);  <span style="white-space:pre"></span>str = "aooooooob";  <span style="white-space:pre"></span>reg = "ao{4,}b";  <span style="white-space:pre"></span>b = str.matches(reg);  <span style="white-space:pre"></span>System.out.println(str + ":" + b);  <span style="white-space:pre"></span>reg = "ao{4,6}b";  <span style="white-space:pre"></span>b = str.matches(reg);  <span style="white-space:pre"></span>System.out.println(str + ":" + b);  <span style="white-space:pre"></span>}  }



正则表达式对String的操作方法


        匹配: 
                matches(String regex);用规则匹配字符串,只要有一处不符合规则,就匹配结束,返回false;
        分割: 
                 split(String regex);根据给正则表达式的匹配拆分字符串,返回一个字符串数组;
        替换: 
                replaceAll(String regex,String replacement);使用给定的replacement替换此字符串所有匹配给定的正则表达式的字符串;
                注:如果regex中有定义组,可以在第二参数中通过“$”符号获取正则表达式中的已有的组;
       获取:将字符串中的符合规则的子串取出; 
       操作步骤: 
               将正则表达式封装成对象;
               让正则对象和要操作的字符串相关联;
               关联后,获取正则匹配引擎;
               通过引擎对符合规则的子串进行操作,比如取出;
class  RegexDemo{    public static void main(String[] args) {        //demo();        //System.out.println((char)11);//      checkTel();        //splitDemo("zhangsan.lisi.wangwu","\\.");        //splitDemo("c:\\abc\\a.txt","\\\\");        //splitDemo("erkktyqqquizzzzzo","(.)\\1+");//按照叠词完成切割。为了可以让规则的结果被重用                                                //可以将规则封装成一个组。用()完成。组的出现都有编号。                                                //从1开始。 想要使用已有的组可以通过  \n(n就是组的编号)的形式来获取。        String str = "wer1389980000ty1234564uiod234345675f";//将字符串中的数组替换成#。     //replaceAllDemo(str,"\\d{5,}","#");        String str1 = "erkktyqqquizzzzzo";//将叠词替换成$.  //将重叠的字符替换成单个字母。zzzz->z        replaceAllDemo(str1,"(.)\\1+","$1");       }    public static void replaceAllDemo(String str,String reg,String newStr){        str = str.replaceAll(reg,newStr);        System.out.println(str);    }    public static void splitDemo(String str,String reg){            //String reg = " +";//按照多个空格来进行切割        String[] arr = str.split(reg);          System.out.println(arr.length);        for(String s : arr){            System.out.println(s);        }    }    /*    匹配    手机号段只有 13xxx 15xxx 18xxxx    */    public static void checkTel(){        String tel = "16900001111";        String telReg = "1[358]\\d{9}";        System.out.println(tel.matches(telReg));    }    public static void demo(){        String str = "b23a23456789";        String reg = "[a-zA-Z]\\d*";        boolean b= str.matches(reg);        System.out.println(b);    }    public static void checkQQ(){        String qq = "123a454";        String regex = "[1-9]\\d{4,14}";        boolean flag = qq.matches(regex);        if(flag)            System.out.println(qq+"...is ok");        else            System.out.println(qq+"... 不合法");    }    /*    对QQ号码进行校验    要求:5~15  0不能开头,只能是数字       这种方式,使用了String类中的方法,进行组合完成了需求。但是代码过于复杂。    */    public static void checkQQ_1(){        String qq = "1882345a0";        int len = qq.length();        if(len>=5 && len<=15){            if(!qq.startsWith("0")){//Integer.parseInt("12a");NumberFormatException                try{                    long l = Long.parseLong(qq);                    System.out.println("qq:"+l);                }catch (NumberFormatException e){                    System.out.println("出现非法字符.......");                }               }else{                System.out.println("不可以0开头");            }        }else{            System.out.println("长度错误");        }    }}

PS:
           Pattern类为正则表达式的编译表示形式。指定为字符串的正则表达式必须首先被编译为此类的实例。然后,可将得到的模式   用于创建Matcher对象,依照正则表达式,该对象可以与任意字符序列匹配。执行匹配所涉及的所有状态都驻留在匹配器中,所以多个匹配器可以共享同一模式。

示例:
public class RegexTest{  <span style="white-space:pre"></span>public static void main(String[] args){  <span style="white-space:pre"></span>test();  <span style="white-space:pre"></span>}  /*  * 1.  治疗口吃:我我 ... 我我 ... 我我我我 ... 要要要要 ... 要要要要 ... 学学学学学 ...学学编编 ... 编编编编 .. 编 .. 编 ... 程程 ... 程程程  * 2.  对 ip 地址排序  * 3.  对邮件地址校验  */  /*  * 1.  治口吃  */  <span style="white-space:pre"></span>public static void test(){  <span style="white-space:pre"></span>String str = " 我我 ... 我我 ... 我我我我 ... 要要要要 ... 要要要要 ... 学学学学学 ... 学学编编 ... 编编编编 .. 编 .. 编 ... 程程 ... 程程程 ";  <span style="white-space:pre"></span>//1.  将字符串中 . 去掉,用替换。  <span style="white-space:pre"></span>str = str.replaceAll("\\.+","");  <span style="white-space:pre"></span>//2.  替换叠词  <span style="white-space:pre"></span>str = str.replaceAll("(.)\\1+","$1");  <span style="white-space:pre"></span>System.out.println(str);  <span style="white-space:pre"></span>}  }




组合捕获

        1.捕获组可以通过从左到右计算器括号类编号 
                    例:在表达式 ((A)(B(C))) 中,存在四个这样的组: 
                            ① ((A)(B(C))) 
                            ② (A) 
                            ③ (B(C)) 
                            ④ (C) 
                           组0始终代表整个表达式。
        2.组的应用: 
                   为了让规则的结果被重用,可以将规则封装成一个组,用()完成,组的出现都有编号,从1开始,想要使用已有的组可以                      通过“\n”(n就是组的编号)的形式来获取
例: 
                            “(a)\1+”;将a封装成组,“1”表示组1编号,“+”表示多个,这个规则的含义是:字符串第一位为“a”,后面跟1个或多                                   个“a”;
                    如果regex中有定义组,可以在第二参数中通过“+n”获取正则表达式中已有的组(n代表组的编号),例:                                                          replaceAll(“(\w)\1+”,”1”);等于replaceAll(“(\w)\1+”,”(\w)”);;


示例:爬虫
import java.util.ArrayList;import java.util.List;import java.io.BufferedReader;import java.io.FileReader;import java.util.regex.Matcher;import java.util.regex.Pattern;import java.io.IOException;  /*  * 网页爬虫:其实就是一个程序用于在互联网中获取符合指定规则的数据。  * 爬取邮箱地址。  */public class RegexTest   public static void main(String[] args) throws IOException {  <span style="white-space:pre"></span>List<String> list = getMails();   <span style="white-space:pre"></span>for(String mail : list){  <span style="white-space:pre"></span>System.out.println(mail);  <span style="white-space:pre"></span>}  }  public static List<String> getMails() throws IOException {  <span style="white-space:pre"></span>//1. 读取源文件。  <span style="white-space:pre"></span>BufferedReader bufr = new BufferedReader(new FileReader("c:\\mail.html"));  <span style="white-space:pre"></span>//2. 对读取的数据进行规则的匹配。从中获取符合规则的数据。  <span style="white-space:pre"></span>String mail_regex = "\\w+@\\w+(\\.\\w+)+";  <span style="white-space:pre"></span>List<String> list = new ArrayList<String>();  <span style="white-space:pre"></span>Pattern p = Pattern.compile(mail_regex);  <span style="white-space:pre"></span>String line = null;  <span style="white-space:pre"></span>while((line = bufr.readLine()) != null){  <span style="white-space:pre"></span>Matcher m = p.matcher(line);  <span style="white-space:pre"></span>while(m.find()){  <span style="white-space:pre"></span>list.add(m.group());  <span style="white-space:pre"></span>}  <span style="white-space:pre"></span>}  <span style="white-space:pre"></span>//3. 将符合规则的数据存储到集合中。  <span style="white-space:pre"></span>return list;  } }



0 0
原创粉丝点击