用示例对Java中的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[] ) {
      //读取字符串值
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input string");
      String input = sc.nextLine();
      //查找数字的正则表达式
      String regex = "(\\d)";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex);
      //打印正则表达式
      System.out.println("Compiled regular expression: "+pattern.toString());
      //验证是否发生匹配
      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 = "Nhooo$";
      String input = "Hi how are you welcome to Nhooo";
      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: Nhooo$