更新時間:2021-04-27 12:37:07 來源:動力節點 瀏覽1293次
正則表達式定義了字符串的模式。正則表達式可以用來搜索、編輯或處理文本。正則表達式并不僅限于某一種語言,但是在每種語言中有細微的差別。Java正則表達式和Perl的是最為相似的。
Java正則表達式的類在 java.util.regex 包中,包括三個類:Pattern,Matcher 和 PatternSyntaxException。
Pattern對象是正則表達式的已編譯版本。他沒有任何公共構造器,我們通過傳遞一個正則表達式參數給公共靜態方法 compile 來創建一個pattern對象。
Matcher是用來匹配輸入字符串和創建的 pattern 對象的正則引擎對象。這個類沒有任何公共構造器,我們用patten對象的matcher方法,使用輸入字符串作為參數來獲得一個Matcher對象。然后使用matches方法,通過返回的布爾值判斷輸入字符串是否與正則匹配。
如果正則表達式語法不正確將拋出PatternSyntaxException異常。
讓我們在一個簡單的例子里看看這些類是怎么用的吧
package com.journaldev.util;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExamples {
public static void main(String[] args) {
// using pattern with flags
Pattern pattern = Pattern.compile("ab", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher("ABcabdAb");
// using Matcher find(), group(), start() and end() methods
while (matcher.find()) {
System.out.println("Found the text \"" + matcher.group()
+ "\" starting at " + matcher.start()
+ " index and ending at index " + matcher.end());
}
// using Pattern split() method
pattern = Pattern.compile("\\W");
String[] words = pattern.split("one@two#three:four$five");
for (String s : words) {
System.out.println("Split using Pattern.split(): " + s);
}
// using Matcher.replaceFirst() and replaceAll() methods
pattern = Pattern.compile("1*2");
matcher = pattern.matcher("11234512678");
System.out.println("Using replaceAll: " + matcher.replaceAll("_"));
System.out.println("Using replaceFirst: " + matcher.replaceFirst("_"));
}
}
既然正則表達式總是和字符串有關, Java 1.4對String類進行了擴展,提供了一個matches方法來匹配pattern。在方法內部使用Pattern和Matcher類來處理這些東西,但顯然這樣減少了代碼的行數。
Pattern類同樣有matches方法,可以讓正則和作為參數輸入的字符串匹配,輸出布爾值結果。
下述的代碼可以將輸入字符串和正則表達式進行匹配。
String str = "bbb";
System.out.println("Using String matches method: "+str.matches(".bb"));
System.out.println("Using Pattern matches method: "+Pattern.matches(".bb", str));
所以如果你的需要僅僅是檢查輸入字符串是否和pattern匹配,你可以通過調用String的matches方法省下時間。只有當你需要操作輸入字符串或者重用pattern的時候,你才需要使用Pattern和Matches類。
注意由正則定義的pattern是從左至右應用的,一旦一個原字符在一次匹配中使用過了,將不會再次使用。
以上就是動力節點小編介紹的“Java正則表達式教程的學習”的內容,希望對大家有幫助,如有疑問,請在線咨詢,有專業老師隨時為您服務。
0基礎 0學費 15天面授
有基礎 直達就業
業余時間 高薪轉行
工作1~3年,加薪神器
工作3~5年,晉升架構
提交申請后,顧問老師會電話與您溝通安排學習