Regex decimal values between 0 and 1 up to 4 decimal places

我怕爱的太早我们不能终老 提交于 2021-02-07 14:20:51

问题


I am writing a C# web application and verify data in a textbox using this regular expression that only accepts positive decimal values between 0 and 1:

^(0(\.\d+)?|1(\.0+)?)$

I would to adapt like the regex to restrict entries to 4 decimal places of precision.

Allowed

0
0.1
0.12
0.123
0.1234
1

Not allowed

-0.1
-1
1.1
2

I have found the following regex that only allows up to 4 decimal places, but I am unsure on how to combine the two.

^(?!0\d|$)\d*(\.\d{1,4})?$

Any help is greatly appreciated, thanks.


回答1:


You need to set replace the + quantifier with the limiting {1,4}:

^(0(\.[0-9]{1,4})?|1(\.0{1,4})?)$
           ^^^^^        ^^^^^ 

See the regex demo

Details:

  • ^ - start of string
  • ( - Outer group start
    • 0 - a zero
    • (\.[0-9]{1,4})? - an optional sequence of a . followed with 1 to 4 digits
    • | - or
    • 1 - a 1
    • (\.0{1,4})?) - an optional sequence of . followed with 1 to 4 zeros
  • $ - end of string.



回答2:


This can be used as the validation function that allows four digit decimal place in terms of regular expession (RegExp).

function fourdecimalplace(e) {
    var val = this.value;
    var re = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?[0-9]?|[0-9]+)$/g;
    var re1 = /^([0-9]+[\.]?[0-9]?[0-9]?[0-9]?[0-9]?|[0-9]+)/g;

    if (re.test(val)) {
        //do something here

    } else {
        val = re1.exec(val);
        if (val) {
            this.value = val[0];
        } else {
            this.value = "";
        }
    }


来源:https://stackoverflow.com/questions/41575948/regex-decimal-values-between-0-and-1-up-to-4-decimal-places

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!