现在的位置: 首页 > 综合 > 正文

Java正则表达式(二)

2013年07月08日 ⁄ 综合 ⁄ 共 10424字 ⁄ 字号 评论关闭

Matcher : 
使用Matcher 类, 最重要的一个概念必须清楚: (Group) , 在正则表达式中 
()
 定义了一个组, 由于一个正则表达式可以包含很多的组, 所以下面先说说怎么划分组的
以及这些组和组的下标怎么对应的
下面我们看看一个小例子, 来说明这个问题

引用

/w(/d/d)(/w+)


这个正则表达式有三个组
整个/w(/d/d)(/w+) 是第0 组 group(0) 
(/d/d)
 是第1 组 group(1) 
(/w+)
 是第2 组 group(2) 
我们看看和正则表达式匹配的一个字符串x99SuperJava , 
group(0)
 永远都是匹配整个表达式的字符串的那部分x99SuperJava 
group(1)
 是第1 组(/d/d) 匹配的部分:99 
group(2)
 是第二组(/w+) 匹配的那部分SuperJava 
下面我们写一个程序来验证一下:

Java 代码

  1. package edu.jlu.fuliang;  
  2.   
  3. import java.util.regex.Matcher;  
  4. import java.util.regex.Pattern;  
  5.   
  6.   
  7. public class RegexTest {  
  8.     public static void main(String[] args) {  
  9.         String regex = "//w(//d//d)(//w+)";  
  10.         String candidate = "x99SuperJava";  
  11.           
  12.         Pattern p = Pattern.compile(regex);  
  13.         Matcher matcher = p.matcher(candidate);  
  14.         if(matcher.find()){  
  15.             int gc = matcher.groupCount();  
  16.             for(int i = 0; i <= gc; i++)  
  17.                 System.out.println("group " + i + " :" + matcher.group(i));  
  18.         }  
  19.     }  
  20. }  

package edu.jlu.fuliang;

 

import java.util.regex.Matcher;

import java.util.regex.Pattern;

 

 

public class RegexTest {

  public static void main(String[] args) {

   String regex = "//w(//d//d)(//w+)";

   String candidate = "x99SuperJava";

  

   Pattern p = Pattern.compile(regex);

   Matcher matcher = p.matcher(candidate);

   if(matcher.find()){

     int gc = matcher.groupCount();

     for(int i = 0; i <= gc; i++)

       System.out.println("group " + i + " :" + matcher.group(i));

   }

  }

}


输出结果:

引用

group 0<!-- [if gte vml 1]><v:shapetype id="_x0000_t75" coordsize="21600,21600" o:spt="75" o:preferrelative="t" path="m@4@5l@4@11@9@11@9@5xe" filled="f" stroked="f"> <v:stroke joinstyle="miter"/> <v:formulas> <v:f eqn="if lineDrawn pixelLineWidth 0"/> <v:f eqn="sum @0 1 0"/> <v:f eqn="sum 0 0 @1"/> <v:f eqn="prod @2 1 2"/> <v:f eqn="prod @3 21600 pixelWidth"/> <v:f eqn="prod @3 21600 pixelHeight"/> <v:f eqn="sum @0 0 1"/> <v:f eqn="prod @6 1 2"/> <v:f eqn="prod @7 21600 pixelWidth"/> <v:f eqn="sum @8 21600 0"/> <v:f eqn="prod @7 21600 pixelHeight"/> <v:f eqn="sum @10 21600 0"/> </v:formulas> <v:path o:extrusionok="f" gradientshapeok="t" o:connecttype="rect"/> <o:lock v:ext="edit" aspectratio="t"/> </v:shapetype><v:shape id="_x0000_i1025" type="#_x0000_t75" alt="" style='width:14.25pt; height:14.25pt'> <v:imagedata src="file:///C:/DOCUME~1/王伟/LOCALS~1/Temp/msohtml1/02/clip_image001.gif" o:href="http://fuliang.javaeye.com/images/smiles/icon_mad.gif"/> </v:shape><![endif]--><!-- [if !vml]--><!-- [endif]-->99SuperJava 
group 1 :99 
group 2 :SuperJava

下面我们看看Matcher 类提供的方法: 
public Pattern pattern() 
这个方法返回了,创建Matcher 的那个pattern 对象。 
下面我们看看一个小例子来说明这个结果

Java 代码

  1. import java.util.regex.*;  
  2.   
  3. public class MatcherPatternExample{  
  4.   public static void main(String args[]){  
  5.       test();  
  6.   }  
  7.   
  8.   public static void test(){  
  9.      Pattern p = Pattern.compile("//d");  
  10.      Matcher m1 = p.matcher("55");  
  11.      Matcher m2 = p.matcher("fdshfdgdfh");  
  12.   
  13.      System.out.println(m1.pattern() == m2.pattern());  
  14.      //return true  
  15.   }  
  16. }  

import java.util.regex.*;

 

public class MatcherPatternExample{

  public static void main(String args[]){

      test();

  }

 

  public static void test(){

     Pattern p = Pattern.compile("//d");

     Matcher m1 = p.matcher("55");

     Matcher m2 = p.matcher("fdshfdgdfh");

 

     System.out.println(m1.pattern() == m2.pattern());

     //return true

  }

}


public Matcher reset() 
这个方法将Matcher 的状态重新设置为最初的状态。 
public Matcher reset(CharSequence input) 
重新设置Matcher 的状态,并且将候选字符序列设置为input 后进行Matcher, 
这个方法和重新创建一个Matcher 一样,只是这样可以重用以前的对象。 
public int start() 
这个方法返回了,Matcher 所匹配的字符串在整个字符串的的开始下标: 
下面我们看看一个小例子

Java 代码

  1. public class MatcherStartExample{  
  2.   public static void main(String args[]){  
  3.       test();  
  4.   }  
  5.   public static void test(){  
  6.      //create a Matcher and use the Matcher.start() method  
  7.      String candidateString = "My name is Bond. James Bond.";  
  8.      String matchHelper[] =  
  9.       {"          ^","                      ^"};  
  10.      Pattern p = Pattern.compile("Bond");  
  11.      Matcher matcher = p.matcher(candidateString);  
  12.   
  13.      //Find the starting point of the first 'Bond'  
  14.       matcher.find();  
  15.       int startIndex = matcher.start();  
  16.       System.out.println(candidateString);  
  17.       System.out.println(matchHelper[0] + startIndex);  
  18.   
  19.      //Find the starting point of the second 'Bond'  
  20.       matcher.find();  
  21.       int nextIndex = matcher.start();  
  22.       System.out.println(candidateString);  
  23.       System.out.println(matchHelper[1] + nextIndex);  
  24. }  

public class MatcherStartExample{

  public static void main(String args[]){

      test();

  }

  public static void test(){

     //create a Matcher and use the Matcher.start() method

     String candidateString = "My name is Bond. James Bond.";

     String matchHelper[] =

      {"          ^","                      ^"};

     Pattern p = Pattern.compile("Bond");

     Matcher matcher = p.matcher(candidateString);

 

     //Find the starting point of the first 'Bond'

      matcher.find();

      int startIndex = matcher.start();

      System.out.println(candidateString);

      System.out.println(matchHelper[0] + startIndex);

 

     //Find the starting point of the second 'Bond'

      matcher.find();

      int nextIndex = matcher.start();

      System.out.println(candidateString);

      System.out.println(matchHelper[1] + nextIndex);

}


输出结果: 
My name is Bond. James Bond. 
          ^11 
My name is Bond. James Bond. 
                      ^23 
public int start(int group) 
这个方法可以指定你感兴趣的sub group, 然后返回sup group 匹配的开始位置。 
public int end() 
这个和start() 对应,返回在以前的匹配操作期间,由给定组所捕获子序列的最后字符之后的偏移量。 
其实start 和end 经常是一起配合使用来返回匹配的子字符串。 
public int end(int group) 
public int start(int group) 对应,返回在sup group 匹配的子字符串最后一个字符在整个字符串下标加一 
public String group() 
返回由以前匹配操作所匹配的输入子序列。 
这个方法提供了强大而方便的工具,他可以等同使用start 和end, 然后对字符串作substring(start,end) 操作。 
看看下面一个小例子:

Java 代码

  1. import java.util.regex.*;  
  2.   
  3. public class MatcherGroupExample{  
  4.   public static void main(String args[]){  
  5.       test();  
  6.   }  
  7.   public static void test(){  
  8.       //create a Pattern  
  9.       Pattern p = Pattern.compile("Bond");  
  10.   
  11.       //create a Matcher and use the Matcher.group() method  
  12.       String candidateString = "My name is Bond. James Bond.";  
  13.       Matcher matcher = p.matcher(candidateString);  
  14.       //extract the group  
  15.       matcher.find();  
  16.       System.out.println(matcher.group());  
  17.   }  
  18. }  

import java.util.regex.*;

 

public class MatcherGroupExample{

  public static void main(String args[]){

      test();

  }

  public static void test(){

      //create a Pattern

      Pattern p = Pattern.compile("Bond");

 

      //create a Matcher and use the Matcher.group() method

      String candidateString = "My name is Bond. James Bond.";

      Matcher matcher = p.matcher(candidateString);

      //extract the group

      matcher.find();

      System.out.println(matcher.group());

  }

}


public String group(int group) 
这个方法提供了强大而方便的工具,可以得到指定的group 所匹配的输入字符串 
应为这两个方法经常使用,同样我们看一个小例子:

Java 代码

  1. import java.util.regex.*;  
  2.   
  3. public class MatcherGroupParamExample{  
  4.   public static void main(String args[]){  
  5.       test();  
  6.   }  
  7.   public static void test(){  
  8.      //create a Pattern  
  9.       Pattern p = Pattern.compile("B(ond)");  
  10.   
  11.      //create a Matcher and use the Matcher.group(int) method  
  12.      String candidateString = "My name is Bond. James Bond.";  
  13.      //create a helpful index for the sake of output  
  14.      Matcher matcher = p.matcher(candidateString);  
  15.      //Find group number 0 of the first find  
  16.       matcher.find();  
  17.       String group_0 = matcher.group(0);  
  18.       String group_1 = matcher.group(1);  
  19.       System.out.println("Group 0 " + group_0);  
  20.       System.out.println("Group 1 " + group_1);  
  21.       System.out.println(candidateString);  
  22.   
  23.      //Find group number 1 of the second find  
  24.       matcher.find();  
  25.       group_0 = matcher.group(0);  
  26.       group_1 = matcher.group(1);  
  27.       System.out.println("Group 0 " + group_0);  
  28.       System.out.println("Group 1 " + group_1);  
  29.       System.out.println(candidateString);  
  30.   }  
  31. }  

import java.util.regex.*;

 

public class MatcherGroupParamExample{

  public static void main(String args[]){

      test();

  }

  public static void test(){

     //create a Pattern

      Pattern p = Pattern.compile("B(ond)");

 

     //create a Matcher and use the Matcher.group(int) method

     String candidateString = "My name is Bond. James Bond.";

     //create a helpful index for the sake of output

     Matcher matcher = p.matcher(candidateString);

     //Find group number 0 of the first find

      matcher.find();

      String group_0 = matcher.group(0);

      String group_1 = matcher.group(1);

      System.out.println("Group 0 " + group_0);

      System.out.println("Group 1 " + group_1);

      System.out.println(candidateString);

 

     //Find group number 1 of the second find

      matcher.find();

      group_0 = matcher.group(0);

      group_1 = matcher.group(1);

      System.out.println("Group 0 " + group_0);

      System.out.println("Group 1 " + group_1);

      System.out.println(candidateString);

  }

}

public int groupCount() 
这个方法返回了,正则表达式的匹配的组数。 
public boolean matches() 
尝试将整个区域与模式匹配。这个要求整个输入字符串都要和正则表达式匹配。 
find 不同, find 是会在整个输入字符串查找匹配的子字符串。 
public boolean find() 
find
 会在整个输入中寻找是否有匹配的子字符串,一般我们使用find 的流程:

Java 代码

  1. while(matcher.find()){  
  2.    // 在匹配的区域,使用group,replace 等进行查看和替换操作  
  3. }  

  while(matcher.find()){

    // 在匹配的区域,使用group,replace 等进行查看和替换操作

  }


public boolean find(int start) 
从输入字符串指定的start 位置开始查找。 
public boolean lookingAt() 
基本上是matches 更松约束的一个方法,尝试将从区域开头开始的输入序列与该模式匹配 
public Matcher appendReplacement (StringBuffer sb, String replacement) 
你想把My name is Bond. James Bond. I would like a martini 中的Bond 换成Smith

Java 代码

  1. StringBuffer sb = new StringBuffer();  
  2. String replacement = "Smith";  
  3. Pattern pattern = Pattern.compile("Bond");  
  4. Matcher matcher =pattern.matcher("My name is Bond. James Bond. I would like a martini.");  
  5. while(matcher.find()){  
  6.   matcher.appendReplacement(sb,replacement);// 结果是My name is Smith. James Smith  
  7. }  

StringBuffer sb = new StringBuffer();

String replacement = "Smith";

Pattern pattern = Pattern.compile("Bond");

Matcher matcher =pattern.matcher("My name is Bond. James Bond. I would like a martini.");

while(matcher.find()){

  matcher.appendReplacement(sb,replacement);// 结果是My name is Smith. James Smith

}


Matcher
 对象会维护追加的位置,所以我们才能不断地使用appendReplacement 来替换所有的匹配。 
public StringBuffer appendTail(StringBuffer sb) 
这个方法简单的把为匹配的结尾追加到StringBuffer 中。在上一个例子的最后再加上一句: 
matcher.appendTail(sb); 
结果就会成为My name is Smith. James Smith. I would like a martini. 
public String replaceAll(String replacement) 
这个是一个更方便的方法,如果我们想替换所有的匹配的话,我们可以简单的使用replaceAll 就ok 了。 
是:

Java 代码

  1. while(matcher.find()){  
  2.   matcher.appendReplacement(sb,replacement);// 结果是My name is Smith. James Smith  
  3. }  
  4. matcher.appendTail(sb);  

while(matcher.find()){

  matcher.appendReplacement(sb,replacement);// 结果是My name is Smith. James Smith

}

matcher.appendTail(sb);


的更便捷的方法。

Java 代码

  1. public String replaceFirst(String replacement)  

public String replaceFirst(String replacement)


这个与replaceAll 想对应很容易理解,就是只替换第一个匹配的。

抱歉!评论已关闭.