Java Pattern compile(String)方法及示例

来源:这里教程网 时间:2026-02-17 21:05:10 作者:

Java Pattern compile(String)方法及示例

Java中 Pattern 类的 compile(String) 方法是用来从作为参数传递给方法的正则表达式中创建一个模式。每当你需要将一个文本与正则表达式模式进行多次匹配时,请使用Pattern.compile()方法创建一个Pattern实例。
语法

public static Pattern compile(String regex)

参数: 该方法接受一个单参数 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)

相关推荐