public static void main(String[] args) {
List<String> inputs = List.of("AaA.BbB.CcC.DdD.EeE", "a1.b2.c3.d4.e5", "AaA.BbB.CcC.DdD.EeE.writing", "a1.b2.c3.d4.e5.writing");
for (String input: inputs) {
printResult(input);
}
}
private static void printResult(String input) {
// Pattern allowedPattern = Pattern.compile("^(?:\\w+\\.)+\\w+$"); -> \\w will match 'A word character: [a-zA-Z_0-9]'
// Pattern allowedPattern = Pattern.compile("^(?:[a-zA-Z0-9]+\\.){4}[a-zA-Z0-9]+$"); -> if you know that it always going to be 4 sections with ending dot, and the last section with no dot
Pattern allowedPattern = Pattern.compile("^(?:[a-zA-Z0-9]+\\.)+[a-zA-Z0-9]+$");
Pattern notAllowedSuffixPattern = Pattern.compile("\\.writing$");
System.out.println("Incoming input: " + input);
String result = (!notAllowedSuffixPattern.matcher(input).find() && allowedPattern.matcher(input).find())
? "Matching.\n"
: "Not Matching!\n";
System.out.println(result);
}
输出量:
Incoming input: AaA.BbB.CcC.DdD.EeE
Matching.
Incoming input: a1.b2.c3.d4.e5
Matching.
Incoming input: AaA.BbB.CcC.DdD.EeE.writing
Not Matching!
Incoming input: a1.b2.c3.d4.e5.writing
Not Matching!
3条答案
按热度按时间nle07wnf1#
你举的例子不太对。
[\d\w]
冗余:\d
是[0-9]
,但\w
已经与[a-zA-Z_0-9]
匹配,你说
AaA.BbB.CcC.DdD.EeE.writing
或a1.b2.c3.d4.e5.writing
不应该由于.writing
后缀。现在如果你只关心它是否匹配,那么你可以检查是否有一个匹配的禁止结束和否定你下面的逻辑。
hwamh0ep2#
可选正则表达式:
“^(?:\w+.)+\w+$”和“.writing$”
测试平台和上下文中的正则表达式:
输出量:
t98cgbkg3#
grep
: