天天看點

JDK6筆記(4)----正規表達式2

JDK6筆記(4)----正規表達式2

一、組group

1、組是由圓括号分開的正規表達式,随後可以根據它們的組号進行調用。

第0組比對整個表達式,第1組比對第1個圓括号擴起來的組,......依次類推。

如:A(B(C))D

有3個組:

第0組:ABCD

第1組:BC

第2組:C

例子:

package myfile;

import java.util.regex.*;

public class GroupR2 {

 public static void main(String[] args) {

  String[] input=new String[]{

    "Java has regular expressions in 1.4",

    "regular expressions now expressing in Java",

    "Java represses oracular expressions"

  };

  Pattern

  p1=Pattern.compile("re//w*"),

  p2=Pattern.compile("Java.*");

  for(int i=0;i

   System.out.println("input "+i+":"+input[i]);

   Matcher

   m1=p1.matcher(input[i]),

   m2=p2.matcher(input[i]);

   while(m1.find())

    System.out.println("m1.find() '"+m1.group()+"' start= "+m1.start()+" end= "+m1.end());

   while(m2.find())

    System.out.println("m2.find() '"+m2.group()+"' start= "+m2.start()+" end= "+m2.end());

   if(m1.lookingAt())

    System.out.println("m1.lookingAt() start = "+m1.start()+" end= "+m1.end());

   if(m2.lookingAt())

    System.out.println("m2.lookingAt() start = "+m2.start()+" end= "+m2.end());

   if(m1.matches())

    System.out.println("m1.matches() start= "+m1.start()+" end= "+m1.end());

   if(m2.matches())

    System.out.println("m2.matches() start= "+m2.start()+" end= "+m2.end());

  }

 }

 /**

 * 輸u20986 結u26524 :

 input 0:Java has regular expressions in 1.4

 m1.find() 'regular' start= 9 end= 16

 m1.find() 'ressions' start= 20 end= 28

 m2.find() 'Java has regular expressions in 1.4' start= 0 end= 35

 m2.lookingAt() start = 0 end= 35

 m2.matches() start= 0 end= 35

 input 1:regular expressions now expressing in Java

 m1.find() 'regular' start= 0 end= 7

 m1.find() 'ressions' start= 11 end= 19

 m1.find() 'ressing' start= 27 end= 34

 m2.find() 'Java' start= 38 end= 42

 m1.lookingAt() start = 0 end= 7

 input 2:Java represses oracular expressions

 m1.find() 'represses' start= 5 end= 14

 m1.find() 'ressions' start= 27 end= 35

 m2.find() 'Java represses oracular expressions' start= 0 end= 35

 */

}

2、Matcher對象的方法:

int groupCount()    分組的數目(不含0組)

String group()    傳回前一次的比對操作

String group(int i)    傳回前一次比對操作期間指定的組

int start(int group)    傳回前一次比對操作尋找到的組的起始下标

int end(int group)    傳回前一次比對操作尋找到的組的最後一個字元下标加一的值

二、模式标記

Pattern Pattern.compile(String regex, int flag)

flag有多個值:

(1)Pattern.CANON_EQ   兩個字元當且僅當它們的完全規範分解相比對時,就認為比對。預設時,不考慮。

(2)Pattern.CASE_INSENSITIVE   預設時,僅在ASCII字元集中進行。

(3)Pattern.COMMENTS   忽略空格符,且以#号開始到行末的注釋也忽略

(4)Pattern.DOTALL     表達式'.'比對所有字元,包括行終結符。預設時,'.'不比對行終結符。

(5)Pattern.MULTILINE  在多行模式下,表達式‘^'和'$'分别比對一行的開始和結束。預設時,它們僅比對輸入的完整字元串的開始和結束。

見例子:

public class ReFlags {

  String str="java has regex/nJava has regex/n" +

    "JaVa has pretty good regular expressions/n"+

    "Regular expressions are in JAva";

  Pattern p=Pattern.compile("^java", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE);

  Matcher m=p.matcher(str);

  while(m.find()) //find()嘗u-29739 查u25214 與u-29723 模u24335 匹u-28339 的u-28781 入u24207 列u30340 下u19968 個u23376 序u21015 。

   System.out.println(m.group()); //group()返u22238 由u20197 前u21305 配u25805 作u25152 匹u-28339 的u-28781 入u23376 序u21015 。

三、split()

它将輸入字元串斷開成字元串對象數組,斷開邊界由正規表達式确定。

String split(CharSequence charseq);

String split(CharSequence charseq, int limit);

第2種limit限制了分裂的數目。

import java.util.*;

public class SplitDemo {

 static String input="This!!unusual use!!of exclamation!!points";

  System.out.println(Arrays.asList(Pattern.compile("!!").split(input)));

  //Arrays.asList() 傳回一個受指定數組支援的固定大小的清單。

  System.out.println(Arrays.asList(Pattern.compile("!!").split(input,3)));

  System.out.println(Arrays.asList("Aha! String has a split() built in!".split(" ")));

四、替換操作

1)replaceFirst(String replacement)

用replacement替換輸入字元串中最先比對的那部分。

2)replaceAll(String replacement)

用replacement替換輸入字元串中所有的比對部分。

3)appendReplacement(StringBuffer sbuf, String replacement)

逐漸地在sbuf中執行替換

4)appendTail(StringBuffer sbuf,String replacement)

在一個或多個appendReplacement()調用之後被調用,以便複制輸入字元串的剩餘部分。

import java.io.*;

/*!Here's a block of text to use as input to

 * the regular expression matcher. Note that we'll

 * first extract the block of text by looking for

 * the special delimiters, then process the

 * extracted block.!

public class TheReplacements {

 public static void main(String[] args) throws Exception{

  String s="/*!Here's a block of text to use as input to/n"+

  " the regular expression matcher. Note that we'll/n"+

  "first extract the block of text by looking for/n"+

  "the special delimiters, then process the/n"+

  "extracted block.!*/";

  Pattern p=Pattern.compile("///*!(.*)!//*/", Pattern.DOTALL); //用以比對在‘/*!’和‘!*/’之間的所有文本

  Matcher mInput=p.matcher(s);

  if(mInput.find())

   s=mInput.group(1); //Captured by parentheses

  //Replace two or more spaces with a single space:

  s=s.replaceAll(" {2,}"," ");

  //Replace on or more spaces at the beginning of each line with no spaces.Must enable MULTILINE mode.

  s=s.replaceAll("(?m)^+","");

  System.out.println(s);

  s=s.replaceFirst("[aeiou]","(VOWEL1)");

  StringBuffer sbuf=new StringBuffer();

  Pattern p1=Pattern.compile("[aeiou]");

  Matcher m1=p1.matcher(s);

  //Process the find information as you perform the replacements:

  while(m1.find())

   m1.appendReplacement(sbuf, m1.group().toUpperCase());

  //Put in the remainder of the text:

  m1.appendTail(sbuf);

  System.out.println(sbuf);

五、reset()方法,可将現有的Matcher對象應用于一個新的字元序列。

public class Resetting {

  Matcher m=Pattern.compile("[frb][aiu][gx]").matcher("fix the rug with bags");

  while(m.find())

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

  m.reset("fix the rug with bags");

六、在JDK1.4之前,将字元串分離成幾部份的方法是:

利用StringTokenizer将該字元串“用标記斷開”。

public class ReplacingStringTokenizer {

  // TODO 自動生成方法存根

  String input ="But I'm not dead yet! I feel happy!";

  StringTokenizer stoke=new StringTokenizer(input);

  while(stoke.hasMoreElements())

   System.out.println(stoke.nextToken());

  System.out.println(Arrays.asList(input.split(" ")));