Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine whether a string contains an integer?

Tags:

java

Say you have a string that you want to test to make sure that it contains an integer before you proceed with other the rest of the code. What would you use, in java, to find out whether or not it is an integer?

like image 250
Nick Avatar asked Dec 08 '10 14:12

Nick


2 Answers

If you want to make sure that it is only an integer and convert it to one, I would use parseInt in a try/catch. However, if you want to check if the string contains a number then you would be better to use the String.matches with Regular Expressions: stringVariable.matches("\\d")

like image 191
Jonathon Bolster Avatar answered Oct 04 '22 03:10

Jonathon Bolster


You can check whether the following is true: "yourStringHere".matches("\\d+")

like image 40
dimitrisli Avatar answered Oct 04 '22 02:10

dimitrisli