问题
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 start0- a zero(\.[0-9]{1,4})?- an optional sequence of a.followed with 1 to 4 digits|- or1- a1(\.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