黑马程序员--JAVA正则表达式

来源:互联网 发布:在线音乐剪辑合成软件 编辑:程序博客网 时间:2024/05/21 10:51


----------- android培训、java培训、java学习型技术博客、期待与您交流! ------------

正则表达式

定义:用来操作字符串的一些规则,符合一定规则的表达式。

作用 :用于专门操作字符串
好处:正则的出现,可以简化对字符串的复杂操作
特点:用于一些特定的符号来表示一些代码操作,这样就简化书写。所以学习正则表达式,就是在学习一些特殊符号的使用。

弊端:符号定义越多,正则越长,阅读性越差。符号的出现虽然简化了书写,但是却降低了阅读性。其实更多是用正则解决字符串操作的问题。
组:用小括号标示,每定义一个小括号,就是一个组,而且有自动编号,从1开始。只要使用组,对应的数字就是使用该组的内容。别忘了,数组要加\\。(aaa(wwww(ccc))(eee))技巧,从左括号开始数即可。有几个左括号就是几组。

具体操作功能
1,匹配:boolean matches(String regex) 方法,(告知此字符串是否匹配给定的正则表达式)用规则匹配整个字符串,只要有一处不符合规则,就匹配结束,返回false
 2,切割:string split(String  reges)根据正则表达式的匹配拆分此字符串
            String[]split(String reges,int linit)根据匹配给定的正则表达式来拆分此字符串。
 3,替换:String replaceAll(String reges ,String replacement)使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串。
 4,获取:
1) 先要将正则表达式编译成正则对象。使用的是Pattern中静态方法 compile(regex);
2) 通过Pattern对象获取Matcher对象。
      Pattern用于描述正则表达式,可以对正则表达式进行解析。而将规则操作字符串,需要从新封装到匹配器对象Matcher中。然后使用Matcher对象的方法来操作字符串。
      如何获取匹配器对象呢?
      通过Pattern对象中的matcher方法。该方法可以正则规则和字符串想关联。并返回匹配器对象。
 3) 使用Matcher对象中的方法即可对字符串进行各种正则操作。

范例:

对QQ号码进行校验
 要求5-15,0补能开头,只能是数字

public class RegexDemo {       public static void main(String[] args) {        checkQQ();             /*splitDemo();            splitDemo("zhangsan  wangwu lisi","\\.");*/             //splitDemo("c:\\abc\\a.txt","\\\\");             splitDemo("erkktykkuio","(.)\\1+");//按照叠词kk完成切割。为了可以让规则的结果被重用               //可以将规则封装成一个组,用()完成,组的出现都有编号,从1开始,想要使用已有的组可以通过\n(n就是组的编号)的形式来获取。               //((())()),有几个括号,就有几个组。               String str="resagqetr1223dsfs43sdg340dfrg3444234";//将字符串中的数字替换成#             replaceAllDemo(str,"\\d{5,}","#");             String str1="adsfasgkkkkkkkkkasdgiouotisadgakssgasdgaskjgskio";//将叠词替换成&             replaceAllDemo(str1,"(.)\\1+","&");             String str2="adsfasgkkkkkkkkkasdgiouotisadgakssgasdgaskjgskio";//将重叠的字符替换成单个字母。zzz->z;             replaceAllDemo(str2,"(.)\\1+","$1");//用$符号获取组。      }      public static void replaceAllDemo(String str,String reg,String newStr)      {     str=str.replace(reg, newStr);    System.out.println(str);  }  public static void splitDemo(String str,String reg)  {                   //String str="zhangsan  wangwu lisi";20 -1 88                    //String str1="c:\\abc\\a.txt";                   //String reg=" +";按照多个空格进行切割。                      //String reg="\\.";      String[] arr=str.split(reg);      for(String s:arr)      {          System.out.println(s);      }  }      /*匹配手机号       * 手机号段只有13***,15***********88,18***********8*/  public static void checkTel()  {      String tel="";           String telReg="1[358]\\d{9}";           System.out.println(tel.matches(telReg));     }  public static void demo()  {         String str="a";      String reg="[bcd]";//规则一个字符,b,c,d中任何一个。      String reg1="[bcd][a-k]";//规则第二个字符,第二个字符从a-k中一个。      String reg2="\\d";//0-9预定义字符类,要\\出现。      String reg11="[bcd]\\b?";//第二位可能出现一次或一次也没有。      String reg21="[bcd]\\d{4,14}";//0-9预定义字符类,要\\出现。      boolean b=str.matches(reg);      System.out.println(b);      }            /*  对QQ号码进行校验    * 要求5-15,0补能开头,只能是数字    */  public static void checkQQ()  {      String qq="";      String regex="[1-9][0-9]{4,14}";//正则表达式。             boolean flag=qq.matches(regex);           if(flag)      System.out.println(qq+".....is ok");           else       System.out.println(qq+".......不合法");  }    <strong> /*  对QQ号码进行校验  * 要求5-15,0补能开头,只能是数字  * 这种方式使用了string类中的方法进行组合完成了需求,但代码过于复杂*/</strong>          public static void  checkQQ_1()          {                 String qq="12334435 32";                 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("出现非法字符。。。。。。。");        }                 /*char[] arr=qq.toCharArray();           boolean flag=true;        for(int x=0;x<arr.length;x++)         {             if(!(arr[x]>='0'&&arr[x]<='9'))                 flag=false;         }         if(flag)         {             System.out.println("qq:"+qq);         }         else         {             System.out.println("出现非法字符");         }         */        }        else        {                System.out.println("不可以0开头");        }    }    else{System.out.println("长度错误");}  }  }  
 

4,获取:将字符串中的符合规则的子串取出
  操作步骤:
1,将正则表达式封装成对象,
2,让正则对象和要操作的字符串相关联
3,关联后,获取正则匹配引擎
4,通过引擎对符合规则的子串进行操作,比如取出

import java.util.regex.*;  public class RegexDemo2 {      public static void main(String[] args) {          }      public static void getDemo()      {          String str="ming tian jiu yao fang jia le ,da jia.";          System.out.println(str);          String reg="\\b[a-z]{3}\\b";          //将规则封装成对象。          Pattern p=Pattern.compile(reg);          //让正则对象和要作用的字符串str相关联,获取匹配器对象。                 Matcher m=p.matcher(str);                    //System.out.println(m.matches());//其实string类中的matches方法,用的就是pattern和matcher对象来完成的。                //只不过被string的方法封装后,用起来较为简单,但是功能却单一。                /*boolean b=  m.find();//将规则作用到字符串上,并进行符合规则的子串查找                 System.out.println(b);               System.out.println(m.group());//用于获取匹配后结果。                     */                     //System.out.println("matches:"+m.matches());      while(m.find())      {          System.out.println(m.group());          System.out.println(m.start()+"....."+m.end());      }  }  }  

范例:

将下列字符串转成:我要学编程。到底用四种功能中的哪一个呢?或者哪几个呢?
 思路方式:
 1,如果只想知道该字符是否对是错,使用匹配
 2,想要将已有的字符串变成另一个字符串,替换
3,想要按照自定的方式将字符串变成多个字符串,切割,获取规则以外的子串
4,想要拿到符合需求的字符串子串,获取,,获取符合规则的子串

import java.util.TreeSet;  public class RegexTest {      <strong>/**需求:      * 将下列字符串转成:我要学编程。      * 到底用四种功能中的哪一个呢?或者哪几个呢?      * 思路方式:      * 1,如果只想知道该字符是否对是错,使用匹配      * 2,想要将已有的字符串变成另一个字符串,替换      * 3,想要按照自定的方式将字符串变成多个字符串,切割,获取规则以外的子串      * 4,想要拿到符合需求的字符串子串,获取,,获取符合规则的子串      * @param args      */</strong>      public static void main(String[] args) {          String str="我我。。。我。。我。。要。。。要要。。。。要要。。。。学学学。。。。。学学。。。编编编。。。。编编。。。程程。。。程程";          /*将已有字符串变成另一个字符串,使用替换功能          * 1,可以先将.去掉          * 2,在将多个重复的内容变成单个内容          * */          str=str.replace("\\.+", "");          System.out.println(str);          str=str.replace("(.)\\1+", "$1");          System.out.println(str);  <strong>/*  * 192.68.1.254  102.49.23.012  010.23.23.34  4.4.4.2  8.34.53.34  * 将IP地址进行地址段顺序的排序。  * 还按照字符串自然顺序,只要让它们每一段都是3位即可  * 1,按照每一段需要的最多的0进行补齐,那么每一段就会至少保证有3位,  * 2,将每一段只保留3位,这样,所有的IP地址都是每一段3位。  * */</strong>        }      public static void ipSort()      {       String ip="192.68.1.254  102.49.23.012  010.23.23.34  4.4.4.2  8.34.53.34";       ip=ip.replaceAll("(\\d+)", "00$1");       System.out.println(ip);       ip=ip.replaceAll("0*(\\d{3})", "$1");       System.out.println(ip);       String[]arr=ip.split("");       TreeSet<String>ts=new TreeSet<String>();       for(String s:arr)       {           ts.add(s);        }       for(String s:ts)       {          System.out.println(s.replace("0*(\\d+)", "$1"));        }      }   <strong>  /*     * 需求:对邮件地址进行校验     *     * */</strong>      public static void checkMail()      {          String mail="abc123@sina.com";          String reg="[a-zA-Z0-9_]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+";//较为精确的匹配。          String reg1="[a-zA-Z0-9_]+@[a-zA-Z0-9]+(\\.[a-zA-Z]+){1,3}";          String reg2="\\w+@\\w+\\w+";//相对补太精确的匹配。                       //mail.indexOf("@")!=-1;错误的方式。          System.out.println(mail.matches(reg));      }  }  

网页爬虫的范例:

import java.io.*;  import java.net.*;  import java.util.regex.*;  public class RegexTest2 {        <strong>/**网页爬虫(蜘蛛)      * @param args      */</strong>      public static void main(String[] args) throws Exception      {               getMails();      }      public static void getMails_1() throws Exception      {          URL url=new URL("http://192.198.2.3:8080/myweb/mail.html");          URLConnection conn=url.openConnection();          BufferedReader bufIn=new BufferedReader(new InputStreamReader(conn.getInputStream()));          String line=null;          String mailreg="\\w+@\\w+(\\.\\w+)+";          Pattern p=Pattern.compile(mailreg);          while((line=bufIn.readLine())!=null)          {              Matcher m=p.matcher(line);              while(m.find())              {                  System.out.println(m.group());              }                                      //System.out.println(line);          }      }      /*     <strong> * 获取指定文档中的邮件地址      * 使用获取功能pattern matcher </strong>    * */      public static void getMails() throws Exception      {          BufferedReader bufr=new BufferedReader(new FileReader("mail.txt"));          String line=null;          String mailreg="\\w+@\\w+(\\.\\w+)+";          Pattern p=Pattern.compile(mailreg);          while((line=bufr.readLine())!=null)          {              Matcher m=p.matcher(line);              while(m.find())              {                  System.out.println(m.group());              }                                      //System.out.println(line);          }      }  }  

----------------------- android培训、java培训、java学习型技术博客、期待与您交流! ----------------------

详情请查看:http://edu.csdn.net/heima