0

How can I check that the string contains both letters and numbers, both? As in the following example:

nickname1
nick1name
1nickname

I've seen a few examples of patterns, but none solves my problem, even most don't work

The situation is that in the application that I'm creating username must be a letter and number, so I need this...

Niklaus
  • 159
  • 1
  • 2
  • 11

3 Answers3

2

Unicode & Character class

What exactly do you mean by a letter? By a number?

Unicode defines those terms across the various human languages. In Java, the Character class provides convenient access to those definitions.

We can make short work of this using streams. Calling String::codePoints generates an IntStream. We can test each code point for being a letter or digit, until we find one.

String input = "nickname1" ;
boolean hitLetter = input.codePoints().anyMatch( i -> Character.isLetter( i ) ) ;
boolean hitDigit = input.codePoints().anyMatch( i -> Character.isDigit( i ) ) ; ;
boolean containsBoth = ( hitLetter && hitDigit ) ;

See this code run live at IdeOne.com.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
1

Well maybe this can help you

String myUser = "asdsad213213";
if(myUser.matches("^[a-zA-Z0-9]+$")){

 //this is true
}

OR create a pattern

Pattern p = Pattern.compile("^[a-zA-Z0-9]+$");
Matcher m = p.matcher(inputstring);
if (m.find()){
//true
}
Cyrille Con Morales
  • 918
  • 1
  • 6
  • 21
1
private boolean checkUsername(String username)
{
String characters = "^[a-zA-Z]+$";
String numbers = "^[0-9]+$";

return username.matches(numbers) && username.matches(characters);
}

there you go, it first for numbers then for chars and when both exist you get a true value

Sam
  • 31
  • 4