Java 中的模式 COMMENTS 字段示例
javaobject oriented programmingprogramming更新于 2024/5/8 7:40:17
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("给定文本中的数字数量:"+count);
}
}
输出
输入输入数据: sample1 text2 with3 numbers4 in5 between6 给定文本中的数字数量: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("输入您的姓名:");
String name = sc.nextLine();
System.out.println("输入您的出生日期:");
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])/
# 表示日期\n" + "[0-9]{4}$ # 表示年份";
//创建一个 Pattern 对象
Pattern pattern = Pattern.compile(regex, Pattern.COMMENTS);
//创建一个 Matcher 对象
Matcher matcher = pattern.matcher(dob);
boolean result = matcher.matches();
if(result) {
System.out.println("给定的出生日期有效");
} else {
System.out.println("给定的出生日期无效");
}
}
}
输出
输入您的姓名: Krishna 输入您的出生日期: 09/26/1998 给定的出生日期有效
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

