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...
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 .
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
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.