This week's book giveaway is in the Big Data forum.
We're giving away four copies of Elasticsearch in Action and have Radu Gheorghe & Matthew Lee Hinman on-line!
See this thread for details.
The moose likes Java in General and the fly likes regex - only allow numbers & one decimal Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Elasticsearch in Action this week in the Big Data forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "regex - only allow numbers & one decimal" Watch "regex - only allow numbers & one decimal" New topic

regex - only allow numbers & one decimal

Ron Landreth

Joined: Oct 04, 2006
Posts: 3
I am trying to write a regular expression that will only allow numbers and one decimal place (aka dollars and cents). How would I write such an expression?

Thanks in advance.
marc weber

Joined: Aug 31, 2004
Posts: 11343

What have you tried so far?

(See Tutorial - Regular Expressions.)

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
David McCombs
Ranch Hand

Joined: Oct 17, 2006
Posts: 212
Are you looking to do this with the java API or in a more general way?

To write it out on paper it would look something like this:

(0+1+2...+9)*.(0+1+2...+9)(0+1+2...+9), where + is or, * means repeat 0 or more times and the 4 expressions are concatanated.

I don't know if this will be helpful to you, but it does describe what you are looking to do. To convert it into a Java regex, reading the link that Marc supplied should get your problem solved.

"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration."- Stan Kelly-Bootle
Nav Letha

Joined: Oct 22, 2006
Posts: 8
You need to escape"." like "\." else, it will take any single character for decimal.
David McCombs
Ranch Hand

Joined: Oct 17, 2006
Posts: 212
The regex I posted was not implementation specific.
I agree. Here's the link:
subject: regex - only allow numbers & one decimal