tags:

views:

204

answers:

4

I want to validate a number. This number must be from -99.99 to +99.99 but except 0 (zero). I came up with this RegEx expression

[-+]?((\d{1,2}\.?\d{0,1}[1-9])|(\d{0,1}[1-9]))

but it does not handle number of this type:

x0
xy.00

Any idea?

Edit: I am trying to do a restriction for xsd file.

+2  A: 

Try this regular expression:

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

This will allow any number starting with a digit greater than 0 followed by an additional optional digit ([1-9]\d?(\.\d{1,2})?). Or, if it starts with 0, followed by a decimal point and followed by either a sequence that does not allow 00 nor 0 (0\.(\d?[1-9]|[1-9]\d)).

Gumbo
@Gumbo: i made a little change, because numbers "x.y" was not allowed.Replace "\.\d{2}" with "\.\d{1,2}". ---This works for me: [-+]?([1-9]\d?(\.\d{1,2})?|0\.(\d?[1-9]|[1-9]\d))
st.stoqnov
@st.stoqnov: So only numbers with two decimal places are allowed?
Gumbo
@Gumbo: no, number with no, one or two decimal places are allowed.
st.stoqnov
@st.stoqnov: Then your comment “"x.y" was not allowed” is a little distracting.
Gumbo
I meant you example did not allows it.
st.stoqnov
@st.stoqnov: Ah, now it makes sense.
Gumbo
A: 

Well, you can simply add two more cases for the missing numbers ... starting from your original regex,

 [-+]?((\d{1,2}\.?\d{0,1}[1-9])|(\d{0,1}[1-9])|(\d0)|([1-9]\d\.00)|(\d[1-9].00))

BTW rather than \d{1,2} it seems slightly better to write \d\d?; similarly \d? rather than \d{0,1}.

In any case this seems an exercise in pain. Can't you use the regex to verify that this is a number in the format you want it, and use a separate constraint to make it not be zero?

alvherre
A: 

try this

^\d{0,2}(\.\d{1,2})?$/
Amit Ranjan
No. That accepts `0`, `0.0` and `0.00`
Bart Kiers
+3  A: 

Try:

[+-]?([1-9]\d?(\.\d\d?)?|0\.[1-9]\d?||0\.0[1-9])

meaning:

[+-]?                 # optional '+' or '-'
(                     #
  [1-9]\d?(\.\d\d?)?  #   1 - 99.99
  |                   #   OR
  0\.[1-9]\d?         #   0.1 - 0.99
  |                   #   OR
  0\.0[1-9]           #   0.01 - 0.09
)                     #
Bart Kiers
What about numbers `0.10`, `0.11`, … `0.99`?
Gumbo
Indeed, forgot the `\d?` in the second OR-ed part (good catch!).
Bart Kiers
And what about `0.1`, `0.2`, …, `0.9`?
Gumbo
Now you have almost the same expression that I have. :-)
Gumbo
Err, they're covered by `0\.[1-9]\d?`
Bart Kiers
You forgot that in your compact expression.
Gumbo
Yes, they sure look a-like! <not-so-humble>What do they say about great minds?</not-so-humble> `;)`
Bart Kiers
Yes, fixed it in the compact one too, thanks!
Bart Kiers
But yours is a little more comprehensive as you didn’t combine the expressions for decimal places after `0.`.
Gumbo
Yes, especially with number ranges, I like to make it a bit more verbose in favor of clarity.
Bart Kiers