黑马程序员java基础之之正则表达式

来源:互联网 发布:php get上传 编辑:程序博客网 时间:2024/06/07 19:53
------- android培训、java培训、期待与您交流! ----------

1.正则表达式:符合一定规则的表达式,只能用于操作字符串,用特殊的符号来简化书写。
  小练习:对QQ号码进行校验,不能用0开头,5-15位,只能是数字.</span>

   按照之前学习的进行编程:

class RegexDemo{  public static void main(String[] args)  {      checkQQ();   }  public static void checkQQ()    {       String qq="v4598";       int len=qq.length();       if(len>=5 && len<=15)       {          if(!(qq.startsWith("0")))           {              char[] arr=qq.toCharArray();              boolean flag=true;               for(int x=0;x<arr.length;x++)              {                 if(!(arr[x]>='0'&&arr[x]<='9'))                 {flag=false;break;}                             }              if(flag)                {                   System.out.println("qq:"+qq);                 }              else              {                  System.out.println("出现非法字符------");               }                          }           else           {              System.out.println("不能以0开头");           }        }       else       {          System.out.println("qq号码有误");        }    }}


然后可以对出现非法字符部分可以用另一种简单的方法:Ingeter.parse("123a");抛出数字格式异常(NumberFormatException)

<pre name="code" class="java">             /*              char[] arr=qq.toCharArray();              boolean flag=true;               for(int x=0;x<arr.length;x++)              {                 if(!(arr[x]>='0'&&arr[x]<='9'))                 {flag=false;break;}                             }              if(flag)              {System.out.println("qq:"+qq);}              else              {System.out.println("出现非法字符------");}               */              try              {               long l=Long.parseLong(qq);               System.out.println("qq:"+l);                }               catch(NumberFormatException e)               {System.out.println("出现非法字符");}
通过正则表达式可以简化大量代码:

class RegexDemo{   public static void main(String[] args)   {       checkQQ();    }    public static void checkQQ()    {        String qq="0644324623462";        String regex="[1-9][0-9]{4,14}";        boolean flag=qq.matches(regex);        if(flag)        {System.out.println(qq+"--qq is ok --");}        else        {System.out.println(qq+"nonono");}     }}

2正则表达式的操作功能:匹配,只要有一处不符合规则,就匹配结束,返回false

上述校验qq号的匹配功能:

String qq=" "; String reg=" ";   //匹配规则boolean flag= qq.matches(reg);

    练习:校验手机号    要求:以13***,15***,18***开头

class checkpn{    public static void main(String[] args)    {         checktel();     }    public static void checktel()    {          String tel=" ";    //""里是要检测的号码          String reg="1[358]\\d{9} ";  //确定第一位是1,[358]第二位是358中的一位,"\\d{9}"之后都是9位数字          System.out.println(tel.matches(reg))     }}

3. 正则表达式的操作功能:切割split  切割注意的是用一些特殊的符号切割的话,要加上\ 转义一下

     练习:利用重叠字母进行切割

    

class RegexSpilt{  public static void main(String[] args)  {      SplitDemo("idhdihwouuyshjlllllopg");   }  public static void SplitDemo(String str)  {          String reg="(.)\\1+";    //()将要重用的规则结果进行封装成组,然后\1从组的编号1开始,获取重用内容;+重用的组1个或多个      String[] arr=str.split(reg);      for(String s: arr)      {          System.out.println(s);       }   }}

4.替换   String replaceAll(String str,String reg,String newstr)

       练习:将字符串里的数字替换成#

      

public static void main(String[] args)  {      String str="agei135443234dhji23497502475094";     String reg="\\d{5,}";        String newstr="#";      replaceDemo(str,reg,newstr);   }  public static void replaceDemo(String str,String reg,String newstr)  {          str=str.replaceAll(reg,newstr);     System.out.println(str);   }

    

将重叠字母换成单个字母

      replaceDemo("djhdjhhkklsgg","(.)\\1+","$1");    //"$1"获取前1个规则中的第一个组

5.获取:将字符串中符合规则的字符串取出

    步骤:1.将正则表达式封装成对象

                2.让正则表达式和要操作的字符串相关联

               3.关联后,获取正则匹配引擎

              4.通过引擎对符合规则的子串进行操作,比如取出

    练习:将字符串中三个字母组成的单词取出

import java.util.regex.*;class RegexDemo2{   public static void main(String[] args)   {       getDemo();    }    public static void getDemo()    {        String str="ming tian jiu yao fang jia la,da jia.";        String reg="\\b[a-z]{3}\\b";              //将规则封装成对象        Pattern p=Pattern.compile(reg);       //让正则对象和要作用的字符相关联,获取匹配器对象       Matcher m=p.matcher(str);    //匹配器       while(m.find())   //m.find():将规则作用到字符串上,并进行符合规则的子串查找        {       System.out.println(m.group());  //获取匹配后的结果        }    }}

总结  :匹配,获得该字符串是对错

               替换:将已有的字符串变成另一个字符串

              切割: 按自定方式将字符串变成多个字符串,获取规则以外的字符串

              获取:拿到符合规则的字符串子串

 练习1:“我我我...想想要...进进...进进进.....黑...黑...马马马”

class RegexTest1{  public static void main(String[] args)  {    TestDemo();  }  public static void TestDemo()  {     String str="我..我.我.....想想要...进进...进进进.....黑...黑...马马马";         str=str.replaceAll("\\.+","");     System.out.println(str);         str=str.replaceAll("(.)\\1+","$1");     System.out.println(str);  }}

练习2

将ip地址按照地址段的顺序排列

   192.163.102.2  120.132.202.121   120.131.221.45     195.45.34.34   3.4.5.6

import java.util.*;class RegexTest2{  public static void main(String[] args)  {    TestDemo();  }  public static void TestDemo()  {     String ip="192.163.102.2  120.132.202.121   120.131.221.45     195.45.34.34   3.4.5.6";         ip=ip.replaceAll("(\\d+)","00$1");//将所有段地址都添加到3位以上        ip=ip.replaceAll("0*(\\d{3})","$1");//将所有段地址转成3位     System.out.println(ip);     String[] arr=ip.split(" +");  //切割地址并存入数组中           TreeSet<String> ts=new TreeSet<String>();        for(String s: arr)     {       ts.add(s);    <span style="font-family: Arial, Helvetica, sans-serif;">//将地址数组存入集合中</span>      }     for(String s: ts)      {       System.out.println(s.replaceAll("0*(\\d+)","$1"));      }  }}

校验邮件地址
class RegexTest3{   public static void main(String[] args)   {      checkMail();    }   public static void checkMail()   {      String mail="143@dnwfdan.com.cm";      String reg="\\w+@\\w+(\\.\\w+)+";      System.out.println(mail.matches(reg));   }}

网页爬虫的设计

打开TomCat服务器,将数据发送到客户端,然后接收并用正则处理

//网页爬虫import java.io.*;import java.util.regex.*;import java.net.*;class RegexTest4{   public static void main(String[] args)throws Exception   {      getMails_1();   }     public static void getMails_1() throws Exception{URL url=new URL("http://192.168.1.198:8080/MyWeb/IE.html");//新建一个URL对象URLConnection conn=url.openConnection();//获取连接器BufferedReader bufin=new BufferedReader(new InputStreamReader(conn.getInputStream()));//获取输入流      String mailreg="\\w+@\\w+(\\.\\w+)+";//创建邮件规则      Pattern p=Pattern.compile(mailreg);//将规则封装成对象      String line=null;      while((line=bufin.readLine())!=null)      {         Matcher m=p.matcher(line);//让正则对象和要作用的字符串关联,获取匹配器对象         while(m.find())//匹配器进行查找符合规则的字符串         {             System.out.println(m.group());//将匹配结果打印出去          }}     }   public static void getMails()throws Exception   {      BufferedReader buff=new BufferedReader(new FileReader("mail.txt"));      String line=null;            String mailreg="\\w+@\\w+(\\.\\w+)+";//创建邮件规则      Pattern p=Pattern.compile(mailreg);//将规则封装成对象            while((line=buff.readLine())!=null)      {         Matcher m=p.matcher(line);//让正则对象和要作用的字符串关联,获取匹配器对象         while(m.find())//匹配器进行查找符合规则的字符串         {             System.out.println(m.group());//将匹配结果打印出去          }       }   }}



0 0
原创粉丝点击