1、Java 1.4之后的版本引進了一個用于處理正則表達式的包 java.util.regex.*; 該包主要包含三個類:
- Pattern : 用來表示一個經過編譯處理后的正則表達式。通俗一點來說,就是用一個類來表示一個正則表達式,這個類是從正則表達式構造得到的。這個類并沒有public constructor, 如果想得到一個這個類的一個對象則必須調用該類的public static方法:public static Pattern compile(String regex)或者 public static Pattern compile(String regex,int flags)。這兩個方法返回一個Pattern型的對象。
- Matcher : 解釋Pattern并執行匹配、查找工作的類,跟Pattern類一樣,這個類也沒有定義public constructor,要想獲得一個Matcher對象必須調用Pattern類的方法 public Matcher matcher(CharSequence input) 來得到。
- PatternSyntaxException : 一個unchecked exception。當遇到不符和Java正則表達式的語法的時候程序就會拋出這個異常。
2、一個例子(摘自
java.sun.com )
package?regex;
import?java.io.Console;
import?java.util.regex.Pattern;
import?java.util.regex.Matcher;
public?class?RegexTestHarness?{
????public?static?void?main(String?[]?args)?{
????????Console?console?=?System.console();
????????if?(console?==?null)?{
????????????System.err.println("No?console.");
????????????System.exit(1);
????????}
????????while?(true)?{
????????????Pattern?pattern?=?Pattern.compile(console.readLine("%nEnter?your?regex:?"));
????????????Matcher?matcher?=?pattern.matcher(console.readLine("Enter?input?string?to?search:?"));
????????????boolean?found?=?false;
????????????while?(matcher.find())?{
????????????????console.format("I?found?the?text?\"%s\"starting?at?"?+
????????????????????????"index?%d?and?ending?at?index?%d.?%n",?matcher.group(),?matcher.start(),?matcher.end());
????????????????found?=?true;
????????????}
????????????if?(!found)
????????????????console.format("No?match?found.%n");
????????}
????}
}
注:由于這個例子使用了JDK 1.6后才有的方法:System.console(),所以這個例子在eclipse和netbeans都不能正常運行。只有在命令行下才能正確運行。如果想在eclipse和nb下運行,好像可以用System.out/in來代替System.console。