一、正則運算式的介紹
正則運算式(Regular Expression)是一種文本模式,它使用單個字串來描述、匹配一系列匹配某個句法規則的字串,
二 、正則運算式的作用
1.測驗字串內的模式,
例如,可以測驗輸入字串,以查看字串內是否出現電話號碼模式或信用卡號碼模式,這稱為資料驗證,
2.替換文本,
可以使用正則運算式來識別檔案中的特定文本,完全洗掉該文本或者用其他文本替換它,
3.基于模式匹配從字串中提取子字串,
可以查找檔案內或輸入域內特定的文本,
三、JAVA的正則運算式的使用
1.java.util.regex 包的三個類:
Pattern 類:
pattern 物件是一個正則運算式的編譯表示,Pattern 類沒有公共構造方法,要創建一個 Pattern 物件,你必須首先呼叫其公共靜態編譯方法,它回傳一個 Pattern 物件,該方法接受一個正則運算式作為它的第一個引數,
Matcher 類:
Matcher 物件是對輸入字串進行解釋和匹配操作的引擎,與Pattern 類一樣,Matcher 也沒有公共構造方法,你需要呼叫 Pattern 物件的 matcher 方法來獲得一個 Matcher 物件,
PatternSyntaxException:
PatternSyntaxException 是一個非強制例外類,它表示一個正則運算式模式中的語法錯誤,
2.正則運算式的一些基本語法


3.Matcher類的方法
A.索引方法

B.查找方法

C.替換方法

5.PatternSyntaxException 類的方法

6.正則運算式應用的例子
下面是一個對單詞 “cat” 出現在輸入字串中出現次數進行計數的例子:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexMatches
{
private static final String REGEX = "\\bcat\\b";
private static final String INPUT =
"cat cat cat cattie cat";
public static void main( String args[] ){
Pattern p = Pattern.compile(REGEX);
Matcher m = p.matcher(INPUT); // 獲取 matcher 物件
int count = 0;
while(m.find()) {
count++;
System.out.println("Match number "+count);
System.out.println("start(): "+m.start());
System.out.println("end(): "+m.end());
}
}
}
運行結果如下圖所示:

下面的例子說明如何從一個給定的字串中找到數字串:
import java.util.regex.*;
public class RegexMatches {
public static void main(String[] args) {
// TODO Auto-generated method stub
String line = "This order was placed for QT3000! OK?";
String pattern = "\\d+";
Pattern r= Pattern.compile(pattern);
Matcher m = r.matcher(line);
if(m.find()) {
System.out.println(m.group());
}
}
}
下面是運行結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/184842.html
標籤:其他
