包 java.util.regex
包含三個(gè)類,以支持正則表達(dá)式的完整版本。
Pattern
保存正則表達(dá)式的編譯形式。
Matcher
將要匹配的字符串與模式相關(guān)聯(lián),并執(zhí)行實(shí)際匹配。
PatternSyntaxException
表示格式錯(cuò)誤的正則表達(dá)式中的錯(cuò)誤。
沒有公共構(gòu)造函數(shù)的模式是不可變的,可以共享。
Pattern
類包含一個(gè)靜態(tài)compile()方法,它返回一個(gè) Pattern
對象。
compile()
方法是重載的。
static Pattern compile(String regex) static Pattern compile(String regex, int flags)
以下代碼將正則表達(dá)式編譯為Pattern對象:
import java.util.regex.Pattern; public class Main { public static void main(String[] args) { // Prepare a regular expression String regex = "[a-z]@."; // Compile the regular expression into a Pattern object Pattern p = Pattern.compile(regex); } }
compile()方法的第二個(gè)版本設(shè)置修改模式匹配方式的標(biāo)志。
flags參數(shù)是一個(gè)位掩碼,并在Pattern類中定義為int常量。
Flag | 描述 |
---|---|
Pattern.CANON_EQ | 啟用規(guī)范等效。 |
Pattern.CASE_INSENSITIVE | 啟用不區(qū)分大小寫的匹配。 |
Pattern.COMMENTS | 啟用不區(qū)分大小寫的匹配。... |
Pattern.DOTALL | 允許在模式中的空格和注釋。 忽略以#開頭的空格和嵌入的注釋,直到行的結(jié)尾。 |
Pattern.LITERAL | 啟用模式的文字解析。 這個(gè)標(biāo)志使元字符和轉(zhuǎn)義序列作為正常字符。 |
Pattern.MULTILINE | 啟用多行模式。 默認(rèn)情況下,^和$匹配輸入序列的開始和結(jié)束。 此標(biāo)志使模式僅逐行匹配或輸入序列的末尾。 |
Pattern.UNICODE_CASE | 啟用支持Unicode的大小寫。 與CASE_INSENSITIVE標(biāo)志一起,可以根據(jù)Unicode標(biāo)準(zhǔn)執(zhí)行不區(qū)分大小寫的匹配。 |
Pattern.UNICODE_ CHARACTER_CLASS | 啟用預(yù)定義字符類和POSIX字符類的Unicode版本。 設(shè)置此標(biāo)志時(shí),預(yù)定義字符類和POSIX字符類符合Unicode技術(shù)標(biāo)準(zhǔn)。 |
Pattern.UNIX_LINES | 啟用Unix行模式。 設(shè)置此標(biāo)志時(shí),只有\(zhòng) n字符被識(shí)別為行終止符。 |
以下代碼編譯設(shè)置CASE_INSENSTIVE和DOTALL標(biāo)志的正則表達(dá)式。
import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String regex = "[a-z]@."; Pattern p = Pattern.compile(regex, Pattern.CASE_INSENSITIVE|Pattern.DOTALL); } }
import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String args[]) { Pattern p = Pattern.compile("java", Pattern.CASE_INSENSITIVE); String candidateString = "Java. java JAVA jAVA"; Matcher matcher = p.matcher(candidateString); // display the latter match System.out.println(candidateString); matcher.find(11); System.out.println(matcher.group()); // display the earlier match System.out.println(candidateString); matcher.find(0); System.out.println(matcher.group()); } }
上面的代碼生成以下結(jié)果。
更多建議: