简体   繁体   English

如何检查字符串是否同时包含字母和数字?

[英]How to check if a string contains both letters and numbers?

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... 情况是,在我正在创建的用户名应用程序中,用户名必须是字母和数字,因此我需要这个...

Unicode & Character class Unicode和Character

What exactly do you mean by a letter? 一封信到底是什么意思? By a number? 用数字吗?

Unicode defines those terms across the various human languages. Unicode在各种人类语言中定义了这些术语。 In Java, the Character class provides convenient access to those definitions. 在Java中, Character类提供了对这些定义的便捷访问。

We can make short work of this using streams. 我们可以使用流来简化它。 Calling String::codePoints generates an IntStream . 调用String::codePoints生成一个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 . 看到此代码在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 你去了,它首先是数字,然后是字符,当两者都存在时,你得到一个真实的值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM