Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String - See if a string contains only numbers and not letters

I have a string that I load throughout my application, and it changes from numbers to letters and such. I have a simple if statement to see if it contains letters or numbers but, something isn't quite working correctly. Here is a snippet.

String text = "abc";  String number;   if (text.contains("[a-zA-Z]+") == false && text.length() > 2) {     number = text;  } 

Although the text variable does contain letters, the condition returns as true. The and && should eval as both conditions having to be true in order to process the number = text;

==============================

Solution:

I was able to solve this by using this following code provided by a comment on this question. All other post are valid as well!

What I used that worked came from the first comment. Although all the example codes provided seems to be valid as well!

String text = "abc";  String number;   if (Pattern.matches("[a-zA-Z]+", text) == false && text.length() > 2) {     number = text;  } 
like image 675
RedHatcc Avatar asked May 13 '12 22:05

RedHatcc


People also ask

How do you know if a string is only numbers and letters?

Use the test() method on the following regular expression to check if a string contains only letters and numbers - /^[A-Za-z0-9]*$/ . The test method will return true if the regular expression is matched in the string and false otherwise.

How do you check in Java if a string contains a number?

To find whether a given string contains a number, convert it to a character array and find whether each character in the array is a digit using the isDigit() method of the Character class.


1 Answers

If you'll be processing the number as text, then change:

if (text.contains("[a-zA-Z]+") == false && text.length() > 2){ 

to:

if (text.matches("[0-9]+") && text.length() > 2) { 

Instead of checking that the string doesn't contain alphabetic characters, check to be sure it contains only numerics.

If you actually want to use the numeric value, use Integer.parseInt() or Double.parseDouble() as others have explained below.


As a side note, it's generally considered bad practice to compare boolean values to true or false. Just use if (condition) or if (!condition).

like image 94
Adam Liss Avatar answered Oct 14 '22 07:10

Adam Liss