Java正則表達式(二)

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 099SuperJava
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想對應很容易理解,就是隻替換第一個匹配的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章