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
// please check below code
If you guys using the following method to check:
Then what happend with the input of very long String, such as I call this method:
The result is "true", also it is a too-large-size number! The same thing will happen if you using regex to check! So I'd rather using the "parsing" method to check, like this:
And the result is what I expected!
Here is another example upgraded "CraigTP" regex matching with more validations.
We can try replacing all the numbers from the given string with ("") ie blank space and if after that the length of the string is zero then we can say that given string contains only numbers. [If you found this answer helpful then please do consider up voting it] Example:
Here is my class for checking if a string is numeric. It also fixes numerical strings:
Features:
Here you go...
Google's Guava library provides a nice helper method to do this:
Ints.tryParse
. You use it likeInteger.parseInt
but it returnsnull
rather than throw an Exception if the string does not parse to a valid integer. Note that it returns Integer, not int, so you have to convert/autobox it back to int.Example:
However, as of the current release -- Guava r11 -- it is still marked @Beta.
I haven't benchmarked it. Looking at the source code there is some overhead from a lot of sanity checking but in the end they use
Character.digit(string.charAt(idx))
, similar, but slightly different from, the answer from @Ibrahim above. There is no exception handling overhead under the covers in their implementation.