📜  Java中的模式 pattern() 方法及示例

📅  最后修改于: 2022-05-13 01:54:26.994000             🧑  作者: Mango

Java中的模式 pattern() 方法及示例

Java中Pattern类的pattern()方法用于获取编译成创建此模式的正则表达式。我们使用正则表达式来创建模式,并且此方法用于获取相同的源表达式。

句法:

public String pattern()

参数:此方法不接受任何参数。

返回值:此方法返回模式的源正则表达式。

下面的程序说明了 pattern() 方法:
方案一:

// Java program to demonstrate
// Pattern.pattern() method
  
import java.util.regex.*;
  
public class GFG {
    public static void main(String[] args)
    {
  
        // create a REGEX String
        String REGEX = "(.*)(for)(.*)?";
  
        // create the string
        // in which you want to search
        String actualString
            = "code of Machine";
  
        // create pattern
        Pattern pattern1 = Pattern.compile(REGEX);
  
        // find the regular expressio of pattern
        String RegularExpression = pattern1.pattern();
  
        System.out.println("Pattern's RegularExpression = "
                           + RegularExpression);
    }
}
输出:
Pattern's RegularExpression = (.*)(for)(.*)?

方案二:

// 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 = "(.*)(ee)(.*)?";
  
        // create the string
        // in which you want to search
        String actualString
            = "geeks";
  
        // create pattern
        Pattern pattern1 = Pattern.compile(REGEX);
  
        // find the regular expressio of pattern
        String RegularExpression = pattern1.pattern();
  
        System.out.println("Pattern's RegularExpression = "
                           + RegularExpression);
    }
}
输出:
Pattern's RegularExpression = (.*)(ee)(.*)?

参考:
https://docs.oracle.com/javase/10/docs/api/java Java()