當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Pattern compile(String)用法及代碼示例

Java中Pattern類的thw compile(String)方法用於根據作為參數傳遞給方法的正則表達式創建模式。每當您需要將文本與正則表達式模式進行多次匹配時,請使用Pattern.compile()方法創建一個Pattern實例。

用法:

public static Pattern compile(String regex)

參數:此方法接受一個單個參數regex,它代表編譯為模式的給定正則表達式。


返回值:此方法返回從正則表達式編譯的模式作為參數傳遞給該方法。

異常:此方法引發以下異常:

  • PatternSyntaxException:如果表達式的語法無效,則拋出此異常。

以下示例程序旨在說明compile(String)方法:
示例1:

// Java program to demonstrate 
// Pattern.compile() method 
  
import java.util.regex.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a REGEX String 
        String REGEX = ".*www.*"; 
  
        // creare the string 
        // in which you want to search 
        String actualString 
            = "www.geeksforgeeks.org"; 
  
        // compile the regex to create pattern 
        // using compile() method 
        Pattern pattern = Pattern.compile(REGEX); 
  
        // get a matcher object from pattern 
        Matcher matcher = pattern.matcher(actualString); 
  
        // check whether Regex string is 
        // found in actualString or not 
        boolean matches = matcher.matches(); 
  
        System.out.println("actualString "
                           + "contains REGEX = "
                           + matches); 
    } 
}
輸出:
actualString contains REGEX = true

示例2:

// Java program to demonstrate 
// Pattern.compile method 
  
import java.util.regex.*; 
  
public class GFG { 
    public static void main(String[] args) 
    { 
        // create a REGEX String 
        String REGEX = "brave"; 
  
        // creare the string 
        // in which you want to search 
        String actualString 
            = "Cat is cute"; 
  
        // compile the regex to create pattern 
        // using compile() method 
        Pattern pattern = Pattern.compile(REGEX); 
  
        // check whether Regex string is 
        // found in actualString or not 
        boolean matches = pattern 
                              .matcher(actualString) 
                              .matches(); 
  
        System.out.println("actualString "
                           + "contains REGEX = "
                           + matches); 
    } 
}
輸出:
actualString contains REGEX = false

參考: https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html#compile(java.lang.String)



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Pattern compile(String) method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。