当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。