Regex模式是一种有价值的基础工具,可以用于很多类型的文本处理,如匹配、搜索、提取、替换和分析结构化内容. Pattern.matches(String pattern, String resource)方法和String的matches方法都适合一次性使用,但是若重复使用,它们的效率较低。通过使用静态的Pattern.compile(String pattern)方法创建一个Pattern实例可以得到一个更高效的用于执行多次匹配的编译版本的模式。

import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.regex.Matcher;

public class SimpleRegex ...{

public static void main(String[] args) ...{
Scanner sca = new Scanner(System.in);
//匹配一个小于99999的自然数
Pattern pattern = Pattern.compile("/d{1,5}");
Matcher matcher;
System.out.println("请输入数字:");

while (true) ...{
matcher = pattern.matcher(sca.nextLine());

if (!matcher.matches()) ...{// 输入不匹配
System.out.println("必须输入0~99999的数字,输入终止");
break; // 退出循环
}
System.out.println("right");
}
sca.close();
}
}
本文介绍了一种利用正则表达式验证用户输入的有效方法。通过Java的Pattern和Matcher类实现了一个简单的程序,该程序能够检查用户输入是否为小于99999的自然数。这种验证方式对于确保数据质量非常有用。

4295

被折叠的 条评论
为什么被折叠?



