Java正则表达式:匹配百分数,排除0%和100% - 代码示例
可以使用负向零宽断言来排除0%和100%的情况,如下所示:
^(?!0(\.0+)?%|100(\.0+)?%)(\d{1,2}(\.\d{1,2})?|[1-9]\d?(\.\d{1,2})?)%$
解释:
^(?!0(\.0+)?%|100(\.0+)?%):以非0%和100%开头,使用负向零宽断言来排除0%和100%的情况(\d{1,2}(\.\d{1,2})?|[1-9]\d?(\.\d{1,2})?):匹配百分数,支持小数%$:以%结尾
以下是Java测试代码:
String regex = "^(?!0(\.0+)?%|100(\.0+)?%)(\d{1,2}(\.\d{1,2})?|[1-9]\d?(\.\d{1,2})?)%$";
String[] testCases = {"0%", "0.0%", "0.00%", "1%", "10.5%", "50%", "99.99%", "100%", "100.0%", "100.00%"};
for (String testCase : testCases) {
System.out.println(testCase + " -> " + testCase.matches(regex));
}
输出结果:
0% -> false
0.0% -> false
0.00% -> false
1% -> true
10.5% -> true
50% -> true
99.99% -> true
100% -> false
100.0% -> false
100.00% -> false
原文地址: https://www.cveoy.top/t/topic/mwM5 著作权归作者所有。请勿转载和采集!