zoukankan      html  css  js  c++  java
  • Java中的Patter类和Match类

     部分引用自: http://developer.51cto.com/art/200906/131761.htm

    本文将介绍Java正则表达式中的Pattern类与Matcher类。首先我们要清楚指定为字符串的正则表达式必须首先被编译为pattern类的实例。因此如何更好的了解这两个类,是编程人员必须知道的。

    Pattern类说明

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

    因此,典型的调用顺序是

    Pattern p = Pattern.compile("a*b");  
    Matcher m = p.matcher("aaaaab");  
    boolean b = m.matches(); 

    在仅使用一次正则表达式时,可以方便地通过pattern类定义 matches 方法。此方法编译表达式并在单个
    调用中将输入序列与其匹配。语句 
    boolean b = Pattern.matches("a*b", "aaaaab");

    等效于上面的三个语句,尽管对于重复的匹配而言它效率不高,因为它不允许重用已编译的模式。 
    此类的实例是不可变的,可供多个并发线程安全使用。Matcher 类的实例用于此目的则不安全。

    Matcher类说明

    通过调用模式的 matcher 方法从模式创建匹配器。创建匹配器后,可以使用它执行三种不同的匹配操作:

    1  matches   方法尝试将整个输入序列与该模式匹配。

    (注:当调用String的matches()方法时,实际上是调用Pattern的静态方法matches().也就是相当于调Matcher的matches(),所以是整个输入序列与模式匹配.)

    2  lookingAt  尝试将输入序列从头开始与该模式匹配。

    3  find     方法扫描输入序列以查找与该模式匹配的下一个子序列。 

    此类的实例用于多个并发线程是不安全的。

    测试代码

    package test;  

      1 import java.util.regex.Matcher;     
      2 import java.util.regex.Pattern;     
      3 /**     
      4  * java中运用正则表达式的两个重要类:Pattern与Matcher     
      5  * @author fhd001     
      6  */     
      7 public class PatternAndMatcherTest {     
      8      public static void main(String[] args) {     
      9         /*     
     10          * 常用的调用     
     11          */     
     12         Pattern p1 = Pattern.compile("a*b");     
     13         String str1 = "aaaab";     
     14         Matcher m1 = p1.matcher(str1);     
     15         boolean b1 = m1.matches();     
     16         System.out.println(b1);     
     17              
     18         String str2 = "b";     
     19         Matcher m2 = p1.matcher(str2);     
     20         boolean b2 = m2.matches();     
     21         System.out.println(b2);     
     22          /*     
     23          * 另一种调用     
     24          * 等效于上面的语句,尽管对于重复的匹配而言它效率不高,因为它不允许重用已编译的模式。      
     25          * 但它可供多个并发线程安全使用,而上面的调用则就不是安全的.     
     26          */     
     27         boolean b3 = Pattern.matches("a*b", "aaab");     
     28         System.out.println(b3);     
     29              
     30         //Pattern类的pattern方法:从pattern类的实例中返回匹配模式的字符串表示     
     31         String pattern1 = p1.pattern();     
     32         System.out.println(pattern1);     
     33              
     34         //Pattern类的split方法     
     35         String[]arr1 = p1.split("rrrrraaabccccaaaaab");     
     36         for (String string : arr1) {     
     37             System.out.println(string+">>>>");     
     38         }     
     39         /*     
     40          * Matcher类     
     41          *      
     42          * matches方法:       方法尝试将整个输入序列与该模式匹配     
     43          * lookingAt方法: 尝试将输入序列从头开始与该模式匹配,与 matches 方法类似,     
     44          *                  此方法始终从区域的开头开始;与之不同的是,它不需要匹配整个区域。      
     45          * find方法:          方法扫描输入序列以查找与该模式匹配的下一个子序列     
     46          */     
     47         String str3 = "aabbcccaaaaaeeeaaaaaaaaagggga";     
     48         Pattern p3 = Pattern.compile("a+");     
     49         Matcher m3 = p3.matcher(str3);     
     50         boolean bo4 = m3.matches();     
     51         System.out.println("matches方法:  "+bo4);     
     52         /*     
     53          * lookingAt方法,从开头第一个字符进行匹配,匹配成功了不再继续匹配,     
     54          * 从第一个字符开始,匹配失败了,也不继续匹配.不需要匹配整个序列     
     55          */     
     56         boolean bo5 = m3.lookingAt();     
     57         if(bo5){     
     58             //group方法(不带参数)返回的就是匹配的子字符串.     
     59             System.out.println("lookingAt方法:  "+m3.group());     
     60         }     
     61      //find方法:找到一个匹配的子串,还会继续找下一个子串.     
     62         while(m3.find()){     
     63             System.out.println("find方法:  "+m3.group());     
     64         }     
     65      /*     
     66          * 带参数的group方法与不带参数的group方法区别     
     67          * 不带参数的group方法:find方法与lookingAt方法匹配出来的子序列(上面有演示)     
     68          * 带参数的group方法: 返回在以前匹配操作期间由给定组捕获的输入子序列。     
     69          */     
     70         String str6 = "aaabbbccc";     
     71         Pattern p5 = Pattern.compile("(a+)(b+)(c+)");     
     72         Matcher m5 = p5.matcher(str6);     
     73         boolean boo = m5.matches();     
     74         if(boo){     
     75             int k = m5.groupCount()+1;//加1就是把0下标的整个字符序列加上,它也作为一组放在0下标的位置.     
     76             if(k>0){     
     77                 for(int i=0;i                    System.out.println(m5.group(i));     
     78                 }     
     79             }     
     80         }     
     81     }     
     82 }    
    

    结果代码 

    true     
    true     
    true     
    a*b     
    rrrrr>>>>     
    cccc>>>>     
    matches方法:  false     
    lookingAt方法:  aa     
    find方法:  aaaaa     
    find方法:  aaaaaaaaa     
    find方法:  a     
    aaabbbccc     
    aaa     
    bbb     
    ccc 

    >>>>>>>>>>>>>>>

    PatternTest.java

     1 import java.io.BufferedReader;
     2 import java.io.FileInputStream;
     3 import java.io.FileOutputStream;
     4 import java.io.IOException;
     5 import java.io.InputStream;
     6 import java.io.InputStreamReader;
     7 import java.io.OutputStream;
     8 import java.util.regex.Matcher;
     9 import java.util.regex.Pattern;
    10 
    11 public class PatternTest {
    12     public static void main(String[] args) {
    13         try {
    14             replaceInFile("<name>.*</name>","C:\project.xml","<name>BigDataDemo</name>");
    15         } catch (IOException e) {
    16             e.printStackTrace();
    17         }
    18         
    19     }
    20     public static void replaceInFile(String regex, String fileName, String replacement) throws IOException {
    21         InputStream in = new FileInputStream(fileName);
    22         StringBuffer buffer = new StringBuffer();
    23         try {
    24             Pattern p = Pattern.compile(regex);
    25             InputStreamReader inR = new InputStreamReader(in);
    26             BufferedReader buf = new BufferedReader(inR);
    27             String line;
    28             while ((line = buf.readLine()) != null) {
    29                 Matcher matcher = p.matcher(line);
    30                 if (matcher.find()) {
    31                     line = matcher.replaceAll(replacement);
    32                 }
    33                 buffer.append(line).append("
    "); //$NON-NLS-1$
    34             }
    35         } catch (IOException e) {
    36             //
    37         } finally {
    38             in.close();
    39         }
    40 
    41         OutputStream os = new FileOutputStream(fileName);
    42         os.write(buffer.toString().getBytes());
    43         os.close();
    44     }
    45 }

     在C盘的更目录下有一个project.xml文件 

    一开始<name> *****</name>不是BigDataDemo

     1 <?xml version="1.0" encoding="UTF-8"?>
     2 <projectDescription>
     3     <name>BigDataDemo</name>
     4     <comment>
     5 To have ready-to-use Job Designs at your disposal, import the Demo Project include in Talend Open Studio.
     6 
     7 Simply follow the steps below:
     8 
     9     * Launch Talend Open Studio
    10     * In the login window, click on Demo
    11     * Choose Java or Perl Demo Project
    12     * Click on Finish to complete the operation
    13     * Choose the TALENDDEMOJAVA or TALENDDEMOPERL on the &quot;Existing&quot; list
    14     * Click on Ok</comment>
    15     <projects>
    16     </projects>
    17     <buildSpec>
    18     </buildSpec>
    19     <natures>
    20         <nature>org.talend.core.talendnature</nature>
    21     </natures>
    22 </projectDescription>
  • 相关阅读:
    关于晋升的5个建议
    不拘一格:网飞的自由与责任工作法
    博恩·崔西的人生管理课
    老板防止我上班摸鱼,给我装了个chrome插件
    彻底搞懂彻底搞懂事件驱动模型
    python 100 days
    不要懒惰地重复自己
    不要让“追求完美”阻碍你做决策
    Windows上使用Python Terminal(终端控制台) 打印日志带有特殊符号时显示不出来
    Python3 Mysql DBhelper封装
  • 原文地址:https://www.cnblogs.com/DreamDrive/p/4282398.html
Copyright © 2011-2022 走看看