Reputation: 3157
I have come up with the following regexp to accept values with a .25 interval or in quarter format, like 1.25, 10.75, 11.50, 12, 13.
Regular Expression
^\d+((\.0+)*|(\.250*)|(\.50*)|(\.750*))$
Example
Accepted Values = 0, 0.25, 0.50, 0.75, 3 , 1.25 , 1.50, 1.75, 5 , 10
Not Accepted Values = 0.15, 0.20, 0.26, 0.30, 1.30, 1.55
I have the following questions;
How can I make it not accept .25, but accept 0.25?
How can I limit the value to the maximum number? I want it to accept up to 15.5.
Upvotes: 0
Views: 3862
Reputation: 12196
I think Regex is the wrong way to do it, but if you insist then the following should suit you right.
^(\d|1[0-5]?)((\.0+)*|(\.250*)|(\.50*)|(\.750*))$
Upvotes: 0
Reputation: 759
^(0|1)?[1-4]?(|\.0+|\.250*|\.50*|\.750*)$
for matching 0-14 numbers and make a | to match with numbers 15, 15.25, 15.50* with the following:
15(|\.0+|\.250*|\.50*)
The final one will be
^(((0|1)?[1-4]?(|\.0+|\.250*|\.50*|\.750*)) | (15(|\.0+|\.250*|\.50*)))$
Upvotes: 0
Reputation: 593
You can use this regex:
^((?:1[0-4]|[0-9])?(?:\.(?:25|5|75))?0*|15(?:\.(?:25|5)?0*)?)$
Demo: http://regex101.com/r/eQ2pA1/7
Upvotes: 0
Reputation: 22841
This is the wrong way to do this, but a solution nonetheless:
^((1[0-4]|[0-9])?(\.(25|5|75)?0*)?|15(\.(25|5)?0*)?)$
Regex r = new Regex("^((1[0-4]|[0-9])?(\\.(25|5|75)?0*)?|15(\\.(25|5)?0*)?)$");
string[] arr = {".25", "17.545", "3.75000", "19.5", "10.500", "0.25"};
foreach(string s in arr) {
if (r.IsMatch(s)) {
Console.WriteLine(s);
}
}
It gives:
.25
3.75000
10.500
0.25
Upvotes: 0
Reputation: 6175
In my opinion, Regex is not the correct tool for that kind of work. All the values you want to accept are decimal values. Simply parse the entered value as decimal and then check if it's correct regarding your accepted values:
decimal number;
if (Decimal.TryParse(value, out number))
// Check if you're in the correct range
It will be much simpler, and errorproof.
Upvotes: 7