检查字符串是严格的字母数字

时间:2017-03-28 01:45:31

标签: java eclipse java-8

我正在尝试检查字符串(用户输入)是否严格是字母数字。

我尝试了以下检查java

if (str.matches("^[\\p{Alnum}]*$")){
   System.out.println("String is Alphanumeric");
}

这适用于所有后续输入

rfvtgbyhnujm
235675434567
3edc4rfv5tgb
cde3vfr4bgt5

我只想通过3edc4rfv5tgb& cde3vfr4bgt5

几乎所有论坛都提出了这个解决方案,但它对我不起作用。不知道我在这里失踪了什么。

我只想传递纯字母数字字符串,没有特殊字符。

4 个答案:

答案 0 :(得分:3)

您可以使用以下逻辑:

  1. 如果文字以一系列字母字符开头,则必须有一个数字,$this->{$host}();
  2. 如果文字以数字序列开头,则之后必须有字母字符,\p{Alpha}++\p{Digit}
  3. 在这些替代方案中,可能会出现任意字母数字尾随字符:

    \p{Digit}++\p{Alpha}

    测试:

    ^(?:\p{Alpha}++\p{Digit}|\p{Digit}++\p{Alpha})\p{Alnum}*$
    
    String[] samples={ "rfvtgbyhnujm", "235675434567", "3edc4rfv5tgb", "cde3vfr4bgt5" };
    for(String str: samples) {
        if(str.matches("^(?:\\p{Alpha}++\\p{Digit}|\\p{Digit}++\\p{Alpha})\\p{Alnum}*$")) {
            System.out.println(str+" is Alphanumeric");
        }
    }
    

答案 1 :(得分:2)

不确定你的“纯字母数字”是什么意思。如果你的意思是字符串应该包含“alpha”和“numeric”字符,你可以通过使用正向前瞻来做到这一点:

^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$

解释

^                                        start of line
 (?=          )                          positive look ahead
    .*[a-zA-Z]                           any chars followed by alphabets
               (?=       )               another positive look ahead
                  .*[0-9]                any chars followed by digits
                          [a-zA-Z0-9]+   alphanumeric characters
                                      $  till end of line

https://regex101.com/r/YNmBx4/1

中测试一下

使用这种方法的一个优点是,可以很容易地为正则表达式添加更多条件,例如,如果您希望字符串中至少有1个大写字符,只需添加一个正向前瞻(?=.*[A-Z])

答案 2 :(得分:1)

据我了解,您至少需要一个字母和至少一个数字来接受字符串作为字母数字(这不是通常的定义)。考虑到字母或数字可能首先出现,我建议如下。

编辑:灵感来自Holger’s answer我已经介绍了占有量词++。就像(通常的)贪心量词一样,它匹配尽可能多的实例,但与贪婪量词不同,如果找不到完整模式的匹配,则它不会返回并尝试使用更少的实例。这似乎在这里有意义(并提供更好的性能)。

private static final Pattern alphanumPattern 
        = Pattern.compile("(\\p{Alpha}++\\p{Digit}++\\p{Alnum}*)|(\\p{Digit}++\\p{Alpha}++\\p{Alnum}*)");

private static boolean isAplhanumeric(String str) {
    return alphanumPattern.matcher(str).matches();
}

这会传递3edc4rfv5tgbcde3vfr4bgt5,但拒绝rfvtgbyhnujm235675434567

答案 3 :(得分:0)

要匹配仅包含这些字符(或空字符串)的字符串,请尝试以下正则表达式 -

"^[a-zA-Z0-9_]*$"

这适用于.NET正则表达式,也可能适用于许多其他语言。

打破它:

^ : start of string
[ : beginning of character group
a-z : any lowercase letter
A-Z : any uppercase letter
0-9 : any digit
_ : underscore
] : end of character group
* : zero or more of the given characters
$ : end of string

如果您不想允许空字符串,请使用+而不是*。

Pure-Alpha-Numberic 解决方案是:

String input = "3edc4rfv5tgb";
System.out.println("matched :"+Pattern.compile("^(?=.*[a-zA-Z])(?=.*[0-9])[a-zA-Z0-9]+$").matcher(input));