【发布时间】:2015-03-13 06:36:25
【问题描述】:
我正在尝试使用 java regex 类(即 Pattern 和 Matcher)来验证 Utian ID 号。
以下是需要满足的条件,
- 字符串必须以 0-3 个(含)小写字母开头。
- 紧跟字母后面必须有一个数字序列 (0-9),该段的长度必须介于 2 和 8 之间,包括两个端点。
- 数字后面必须至少有 3 个大写字母。
以下是我写的代码,
public class Solution{public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int ntc;
String[] str;
try {
ntc = Integer.parseInt(br.readLine());
str = new String[ntc];
for (int i = 0; i < ntc; i++)
str[i] = br.readLine();
for (int i = 0; i < ntc; i++)
if (validate(str[i]))
System.out.println("VALID");
else
System.out.println("INVALID");
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean validate(String str) {
Pattern pr = Pattern.compile("[a-z]{0,3}[0-9]{2,8}[A-Z]{3,}");
Matcher mr = pr.matcher(str);
return mr.find();
}}
以下是输入及其各自的o/p
I/P: 3
n761512618TUKEFQROSWNFWFWEQEXKPWYYCRK
rRf99
198VLHJIYVEBODQCQEGYGECOGRMQPE
O/P:
有效
无效
有效
第一个测试用例无效,因为它有九个数字,而不是最多八个。但是它说有效。 我写的Regex模式有什么问题吗?
【问题讨论】:
标签: java regex validation