tags:

views:

75

answers:

4

I am trying regex to find out whether a number is divisible by 10 or by 5. So basically, I am trying to see whether the number end in 0 or 5.

This is my regular expression ^[1-9]*0?.0$

I encounter issues when the input is 100.0 or 55.0

What should the regular expression be?

Thanks, Sandy

+1  A: 

^\d*[05](?:\.[0]+)?$

Should work. Note that you said ends in 0 or 5. But said divisible by 10 or by 5. These are not the same thing. Example, 55 is divisible ends in 5 and is divisible by 5, but not 10.

Also note that it would allow for 000100.000. That is to say the leading zeroes are allowed, but technically it is divisible by 5 or 10.

I do agree with the comments. It be much easier to do this will math. Integer division or the modulus operator would be more straightforward.

Jason McCreary
+1  A: 

If you must do this with regexes for some reason, then the answer is:

/^\d*[05]\.0$/
  1. Beginning of string
  2. Any number of digits (including none)
  3. A '0' or '5'
  4. A '.' (note backslash escaping since . is a regex metacharacter)
  5. A '0'
  6. End of string
Thom Smith
+1  A: 

Why not simply do

bool isDivisibleBy5 = ! (number % 5);

? (You didn't specify what language you are using, but that syntax should at least be comprehensible if you come from a C-ish background.)

Ether
+1 for going that Math route ;)
Jason McCreary
A: 

If you know that you are passing integer strings in then there is no need to check any other digits, just whether the digit before the end or decimal point is 5 or 0. Also I'm allowing any amount of 0's after the decimal point, because that's still divisible by 5.

/[05](?:\.0+)?$/
Axeman