tags:

views:

106

answers:

4

decimal seperator is a dot, followed by max one digit! No range specified.

Thanks guys!

+8  A: 
^-?\d+(\.\d)?$

if the decimal part is optional, and

^-?\d+\.\d$

if it's required :)

Artiom Chilaru
You forgot that dot is a special character.
ZyX
Hah, fair enough.. thanks for that.Fixed
Artiom Chilaru
Thanks a lot! Works just fine!
tzippy
Cool, glad it works! :)Btw, if someone answers your questions, you can "accept" their answer.. Just click on the big green "tick" on the left :)
Artiom Chilaru
I don't think you need the start and end anchors (^$) in String.matches(), though they don't do any harm of course.
pdbartlett
RegEx is powerful when you need it, but very cryptic! All I need is to validate a positive or negative integer, and ended up with `^-?\d+` which works. When I see it, I understand what it does, but to come up with this without having a concrete example that is similar to what I want? not easy...
awe
Artiom Chilaru
awe
...and thanks for providing the answer.. It was your answer here that pointed me in the right direction to solve my validator in the first place. My issue was really to get the `-` sign to be optional, so it was the `?` that did the trick for me compared with what I had first.
awe
+2  A: 

Simple: -?\d+\.\d

ZyX
A: 

Did you Google it at all? Is this a homework question?

Alphax
+1  A: 

Unlikely to be relevant in this case, but don't forget that "." is not universal as the decimal separator. Many European countries use "," so you might prefer to get the one in use from the locale:

DecimalFormat df = (DecimalFormat) NumberFormat.getInstance();
String separator = df.getDecimalFormatSymbols().getDecimalSeparator();

(See also: http://java.sun.com/j2se/1.5.0/docs/api/java/text/DecimalFormatSymbols.html#getDecimalSeparator)

pdbartlett
A very valid point, and one that can be a nasty surprise for North American developers.
Tim Drisdelle