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

这个正则表达式使用了负向前瞻,即不匹配 0% 和 100%。同时支持 1 位或 2 位数字,或者 1 位数字加 1 到 2 位小数。

Java 测试代码如下:

public static void main(String[] args) {
    String regex = "(?!0%)(?!100%)([1-9]|[1-9]\d|\d\.\d{1,2})%";
    String[] tests = {"0%", "50%", "100%", "1%", "10%", "99.99%", "101%", "9.8%", "0.01%", "99%"};
    for (String test : tests) {
        System.out.println(test + " matches regex: " + test.matches(regex));
    }
}

输出结果:

0% matches regex: false
50% matches regex: true
100% matches regex: false
1% matches regex: true
10% matches regex: true
99.99% matches regex: true
101% matches regex: false
9.8% matches regex: true
0.01% matches regex: true
99% matches regex: true

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

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