Reputation:
In Java, I'm currently using
str.matches("\\d")
but its only matching a single number.
I need to match ints and doubles, e.g. :
"1"
"1337"
".1"
"13.7"
Any help would be awesome.
Upvotes: 3
Views: 197
Reputation: 11184
((\+|-)?(\d+(\.\d+)?|\.\d+))
This would match positive and negative ints, doubles that start with a digit, and doubles start with a dot
Upvotes: 2
Reputation: 80384
This will match any real number that the Java compiler will recognize. To do this, it also handles things like signed numbers and exponentials. It’s in Pattern.COMMENTS
mode because I think anything else is barbaric.
(?xi) # the /i is for the exponent
(?:[+-]?) # the sign is optional
(?:(?=[.]?[0123456789])
(?:[0123456789]*)
(?:(?:[.])
(?:[0123456789]{0,})
) ?
)
# this is where the exponent starts, if you want it
(?:(?:[E])
(?:(?:[+-]?)
(?:[0123456789]+)
)
|
)
Upvotes: 1
Reputation: 5565
I think this is tidier to look at than the other suggestions, while still doing the same thing.
(\\d+)?(\\.)?\\d+
Upvotes: 1
Reputation: 4939
There is a quite extensive lesson about regular expressions in the Java Tutorials.
For information about matching multiple characters you should read the section about quantifiers.
Upvotes: -1