How would you check if a String was a number before parsing it?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
if you are on android, then you should use:
documentation can be found here
keep it simple. mostly everybody can "re-program" (the same thing).
Parallel checking for very long strings using IntStream
In Java 8, the following tests if all characters of the given
string
are within '0' to '9'. Mind that the empty string is accepted:This is the fastest way i know to check if String is Number or not:
Java 8 lambda expressions.
Parse it (i.e. with
Integer#parseInt
) and simply catch the exception. =)To clarify: The parseInt function checks if it can parse the number in any case (obviously) and if you want to parse it anyway, you are not going to take any performance hit by actually doing the parsing.
If you would not want to parse it (or parse it very, very rarely) you might wish to do it differently of course.
CraigTP's regular expression (shown above) produces some false positives. E.g. "23y4" will be counted as a number because '.' matches any character not the decimal point.
Also it will reject any number with a leading '+'
An alternative which avoids these two minor problems is