English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java中的模式注释字段(带有示例)

Pattern类的COMMENTS字段允许空格和模式中的注释。当将此值用作compile()方法的标志值时,给定模式中的空格和以#开头的注释将被忽略。

例子1

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
   public static void main( String args[] ) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter input data: ");
      String input = sc.nextLine();
      //查找数字的正则表达式
      String regex = "\\d #ignore this comment\n";
      //编译正则表达式
      Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
      //检索匹配器对象
      Matcher matcher = pattern.matcher(input);
      int count = 0;
      String result = "";
      while (matcher.find()) {
         count++;
         result = result+matcher.group();
      }
      System.out.println("Number of digits in the given text: "+count);
   }
}

输出结果

Enter input data:
sample1 text2 with3 numbers4 in5 between6
Number of digits in the given text: 6

例子2

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class COMMENTES_Example {
   public static void main(String[] args) {
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter your name: ");
      String name = sc.nextLine();
      System.out.println("Enter your Date of birth: ");
      String dob = sc.nextLine();
      //正则表达式以MM-DD-YYY格式接受日期
      String regex = "^(1[0-2]|0[1-9])/
         # For Month\n" + "(3[01]|[12][0-9]|0[1-9])/
         # For Date\n" + "[0-9]{4}$ # For Year";
      //创建一个Pattern对象
      Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
      //创建一个Matcher对象
      Matcher matcher = pattern.matcher(dob);
      boolean result = matcher.matches();
      if(result) {
         System.out.println("Given date of birth is valid");
      } else {
         System.out.println("Given date of birth is not valid");
      }
   }
}

输出结果

Enter your name:
Krishna
Enter your Date of birth:
09/26/1989
Given date of birth is valid