help with a simple regular expression

lockmac

Senior member
Dec 5, 2004
603
0
0
Hi guys. I am having trouble grasping regular expression (like many im guessing).

Anyways, I need a regular expression that will accept the following.

A number between 0 and 100 and .5 values are acceptable.

Eg. 40.5 is acceptable but 40.4 or 40.7 is not acceptable.

Thanks very much
 

slugg

Diamond Member
Feb 17, 2002
4,723
80
91
let x = the number...

if(2 * x - (int)(2 * x) || x < 0 || x > 100)
{
number is bad
}
else
{
number is good
}
 

lockmac

Senior member
Dec 5, 2004
603
0
0
thanks for that mate, but i cant use code for it, it has to be regular expression (this is to be used in an xml schema declaration
 

Snapster

Diamond Member
Oct 14, 2001
3,916
0
0
Try

^\d{1,3}(\.[05])?$

matches 1 to 3 decimal numbers at the start and if any decimal point it expects it to be a 0 or a 1, hopefully!
 

presidentender

Golden Member
Jan 23, 2008
1,166
0
76
40.5 is okay. Is 40.0? What about 40?

Regular expressions work on Strings, so this is an important distinction. Assuming you want 40.0 and 0.0 and 100.0, not 40:

([1-9]?[0-9]([.0]|[.5]))|([100.0])|([0.0])

should work. I didn't test it. Check this out.
 

lockmac

Senior member
Dec 5, 2004
603
0
0
Hey snapster- that worked a treat, except that it accepts values over 100, which is okay i guess, i can write some different logic to deal with that.

presidentender, 40 is okay, 40.0 is okay, but 40.4 isnt. Im basically wanting a full number (can have the decimal .0 put their if they want) but it can only increment in halves. Its for a student mark file and half marks are acceptable. and thanks for your string, but it didnt seem to work at all :(
 

Snapster

Diamond Member
Oct 14, 2001
3,916
0
0
Ah yeh, forgot to test over 100 :)

Try this:

^(([0-9]|[0-9][0-9])(\.[05])?|(100)(\.[0])?)$

It should allow 100 and 100.0 but not 100.5 too.