正则表达式匹配百分比 (不含0%和100%):Java示例
正则表达式匹配百分比 (不含0%和100%):Java示例
想要匹配不包含0%和100%的百分比,可以使用以下正则表达式:
^(0\.\d{1,2}|[1-9]\d?\.\d{1,2}|[1-9]\d?)%$
这个正则表达式匹配以下格式的百分比:
- 0.xx% (例如:0.1%, 0.5%)
- xx.xx% (例如:1.23%, 50.5%)
- xx% (例如:50%, 99%)
Java 代码示例:
String regex = "^(0\.\d{1,2}|[1-9]\d?\.\d{1,2}|[1-9]\d?)%$";
Pattern pattern = Pattern.compile(regex);
String[] tests = {"0%", "50%", "99.99%", "100%", "0.1%", "1.23%", "50.5%"};
for (String test : tests) {
Matcher matcher = pattern.matcher(test);
System.out.println(test + " matches: " + matcher.matches());
}
输出结果:
0% matches: false
50% matches: true
99.99% matches: true
100% matches: false
0.1% matches: true
1.23% matches: true
50.5% matches: true
解释:
^匹配字符串的开头(0\.\d{1,2}|[1-9]\d?\.\d{1,2}|[1-9]\d?)匹配三种情况:0\.\d{1,2}匹配 0.xx% (0.01% 到 0.99%)[1-9]\d?\.\d{1,2}匹配 xx.xx% (1.01% 到 99.99%)[1-9]\d?匹配 xx% (1% 到 99%)
%匹配百分号$匹配字符串的结尾
该正则表达式通过限制第一个数字不能为0或1,以及限制小数点后两位数字,从而实现了排除 0% 和 100% 的功能。
希望这个解释能够帮助你理解如何使用正则表达式来匹配百分比。
原文地址: https://www.cveoy.top/t/topic/mwKx 著作权归作者所有。请勿转载和采集!