Java Pattern pattern()方法及实例

Java Pattern pattern()方法及实例

Java中 Pattern 类的 pattern() 方法是用来获取正则表达式的,该表达式被编译后用于创建该模式。我们使用正则表达式来创建模式,这个方法用来获取相同的源表达式。

语法

public String pattern()

参数: 该方法不接受任何东西作为参数。

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

以下程序说明了pattern()方法:
程序1 :

// 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)(.*)?

程序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 = "(.*)(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/util/regex/Pattern.html#pattern()

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程