Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

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; 

}

1 Answer

0 votes
by (46k points)

This is how I would do it:

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

    //...

}

The $ will avoid a partial match e.g; 1B.

Related questions

0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...