可以将正则表达式修改为:^(0.\d{1,2}|[1-9]\d?(.\d{1,2})?)%$

其中,^(0.\d{1,2}|[1-9]\d?(.\d{1,2})?)%$ 这部分表示匹配百分数,包括小数部分。

具体的修改:

  • 将100改为[1-9]\d?(.\d{1,2})?,这部分表示匹配大于等于10的百分数(包括小数部分),不包括100。
  • 将0改为0.\d{1,2},这部分表示匹配小于1的百分数(包括小数部分),不包括0。

Java测试代码:

public class Test {
    public static void main(String[] args) {
        String regex = "^(0\.\d{1,2}|[1-9]\d?(\.\d{1,2})?)%$ ";
        String[] testCases = {"0%", "0.00%", "0.01%", "1.23%", "99%", "99.99%", "100%", "100.00%"};
        for (String testCase : testCases) {
            boolean isMatch = testCase.matches(regex);
            System.out.println(testCase + " is match: " + isMatch);
        }
    }
}

输出结果:

0% is match: false
0.00% is match: true
0.01% is match: true
1.23% is match: true
99% is match: true
99.99% is match: true
100% is match: false
100.00% is match: false

原文地址: https://www.cveoy.top/t/topic/mwKV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录