更新時間:2021-04-27 12:37:07 來源:動力節(jié)點 瀏覽1182次
正則表達式定義了字符串的模式。正則表達式可以用來搜索、編輯或處理文本。正則表達式并不僅限于某一種語言,但是在每種語言中有細微的差別。Java正則表達式和Perl的是最為相似的。
Java正則表達式的類在 java.util.regex 包中,包括三個類:Pattern,Matcher 和 PatternSyntaxException。
Pattern對象是正則表達式的已編譯版本。他沒有任何公共構(gòu)造器,我們通過傳遞一個正則表達式參數(shù)給公共靜態(tài)方法 compile 來創(chuàng)建一個pattern對象。
Matcher是用來匹配輸入字符串和創(chuàng)建的 pattern 對象的正則引擎對象。這個類沒有任何公共構(gòu)造器,我們用patten對象的matcher方法,使用輸入字符串作為參數(shù)來獲得一個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("_"));
}
}
既然正則表達式總是和字符串有關(guān), Java 1.4對String類進行了擴展,提供了一個matches方法來匹配pattern。在方法內(nèi)部使用Pattern和Matcher類來處理這些東西,但顯然這樣減少了代碼的行數(shù)。
Pattern類同樣有matches方法,可以讓正則和作為參數(shù)輸入的字符串匹配,輸出布爾值結(jié)果。
下述的代碼可以將輸入字符串和正則表達式進行匹配。
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匹配,你可以通過調(diào)用String的matches方法省下時間。只有當(dāng)你需要操作輸入字符串或者重用pattern的時候,你才需要使用Pattern和Matches類。
注意由正則定義的pattern是從左至右應(yīng)用的,一旦一個原字符在一次匹配中使用過了,將不會再次使用。
以上就是動力節(jié)點小編介紹的“Java正則表達式教程的學(xué)習(xí)”的內(nèi)容,希望對大家有幫助,如有疑問,請在線咨詢,有專業(yè)老師隨時為您服務(wù)。
初級 202925
初級 203221
初級 202629
初級 203743