Java 中的 Pattern toString() 方法以及示例


**java.util.regex** 包中的 Pattern 類是正則表示式的編譯表示。

此類的 toString() 方法使用編譯當前 Pattern 的正則表示式返回字串表示。

示例1

import java.util.Scanner;
import java.util.regex.Pattern;
public class Example {
   public static void main( String args[] ) {
      //Reading string value
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //Regular expression to find digits
      String regex = "(\d)";
      //Compiling the regular expression
      Pattern pattern = Pattern.compile(regex);
      //Printing the regular expression
      System.out.println("Compiled regular expression: "+pattern.toString());
      //Verifying whether match occurred
      if(pattern.matcher(input).find())
         System.out.println("Given String contains digits");
      else
         System.out.println("Given String does not contain digits");
   }
}

輸出

Enter input string
This 7est contain5 di9its in place of certain charac7er5
Compiled regular expression: (\d)
Given String contains digits

示例 2

import java.util.regex.Pattern;
public class Example {
   public static void main(String args[]) {
      String regex = "Tutorialspoint$";
      String input = "Hi how are you welcome to Tutorialspoint";
      Pattern pattern = Pattern.compile(regex);
      Matcher match = pattern.matcher(input);
      int count = 0;
      if(match.find())
         System.out.println("Match found");
      else
         System.out.println("Match not found");
      System.out.println("regular expression: "+pattern.toString());
   }
}

輸出

Match found
regular expression: Tutorialspoint$

更新於:2019-11-20

147 次瀏覽

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告