正則表達式定義了字符串的模式,可以用來搜索哼蛆、編輯或處理文本构拳。
正則表達式可以用來搜索咆爽、編輯或處理文本。
Java 正則表達式和 Perl 的是最為相似的置森。
java.util.regex 包主要包括以下三個類:
-
Pattern 類:
pattern 對象是一個正則表達式的編譯表示斗埂。Pattern 類沒有公共構造方法。要創(chuàng)建一個 Pattern 對象凫海,你必須首先調用其公共靜態(tài)編譯方法呛凶,它返回一個 Pattern 對象。該方法接受一個正則表達式作為它的第一個參數(shù)行贪。 -
Matcher 類:
Matcher 對象是對輸入字符串進行解釋和匹配操作的引擎把兔。與Pattern 類一樣,Matcher 也沒有公共構造方法瓮顽。你需要調用 Pattern 對象的 matcher 方法來獲得一個 Matcher 對象。 -
PatternSyntaxException:
PatternSyntaxException 是一個非強制異常類围橡,它表示一個正則表達式模式中的語法錯誤暖混。
捕獲組
捕獲組是把多個字符當一個單獨單元進行處理的方法,它通過對括號內的字符分組來創(chuàng)建翁授。
例如拣播,正則表達式 (dog) 創(chuàng)建了單一分組晾咪,組里包含"d","o"贮配,和"g"谍倦。
捕獲組是通過從左至右計算其開括號來編號。例如泪勒,在表達式((A)(B(C)))昼蛀,有四個這樣的組:
- ((A)(B(C)))
- (A)
- (B(C))
- (C)
可以通過調用 matcher 對象的 groupCount 方法來查看表達式有多少個分組。groupCount 方法返回一個 int 值圆存,表示matcher對象當前有多個捕獲組叼旋。
還有一個特殊的組(group(0)),它總是代表整個表達式沦辙。該組不包括在 groupCount 的返回值中夫植。
實例
下面的例子說明如何從一個給定的字符串中找到數(shù)字串:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
public static void main( String args[] ){
// 按指定模式在字符串查找
String line = "This order was placed for QT3000! OK?";
String pattern = "(\\D*)(\\d+)(.*)";
// 創(chuàng)建 Pattern 對象
Pattern r = Pattern.compile(pattern);
// 現(xiàn)在創(chuàng)建 matcher 對象
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
System.out.println("Found value: " + m.group(3) );
} else {
System.out.println("NO MATCH");
}
}
}
Found value: This order was placed for QT3000! OK?
Found value: This order was placed for QT
Found value: 3000
Found value: ! OK?