繁体   English   中英

用于检查字符串是否严格为字母数字的正则表达式

[英]Regex for checking if a string is strictly alphanumeric

如何检查字符串是否仅包含数字和字母,即。 是字母数字吗?

考虑到您想检查 ASCII 字母数字字符,试试这个: "^[a-zA-Z0-9]*$" String.matches(Regex)使用这个 RegEx,如果字符串是字母数字,它将返回 true,否则它将返回 false。

public boolean isAlphaNumeric(String s){
    String pattern= "^[a-zA-Z0-9]*$";
    return s.matches(pattern);
}

如果有帮助,请阅读有关正则表达式的更多详细信息: http : //www.vogella.com/articles/JavaRegularExpressions/article.html

为了与 Unicode 兼容:

^[\pL\pN]+$

在哪里

\pL stands for any letter
\pN stands for any number

现在是 2016 年或更晚,事情已经有了进展。 这匹配 Unicode 字母数字字符串:

^[\\p{IsAlphabetic}\\p{IsDigit}]+$

请参阅参考资料(“Unicode 脚本、块、类别和二进制属性的类”部分)。 还有这个答案我觉得很有帮助。

请参阅Pattern的文档。

假设 US-ASCII 字母表 (az, AZ),您可以使用\\p{Alnum}

检查一行是否仅包含此类字符的正则表达式是"^[\\\\p{Alnum}]*$"

这也匹配空字符串。 排除空字符串: "^[\\\\p{Alnum}]+$"

使用字符类:

^[[:alnum:]]*$
Pattern pattern = Pattern.compile("^[a-zA-Z0-9]*$");
Matcher matcher = pattern.matcher("Teststring123");
if(matcher.matches()) {
     // yay! alphanumeric!
}

试试这个 [0-9a-zA-Z]+ only alpha and num with one char at-least ..

可能需要修改所以测试它

http://www.regexplanet.com/advanced/java/index.html

Pattern pattern = Pattern.compile("^[0-9a-zA-Z]+$");
Matcher matcher = pattern.matcher(phoneNumber);
if (matcher.matches()) {

}

要考虑所有 Unicode 字母和数字,可以使用Character.isLetterOrDigit 在 Java 8 中,这可以与String#codePointsIntStream#allMatch结合使用。

boolean alphanumeric = str.codePoints().allMatch(Character::isLetterOrDigit);

要包括[a-zA-Z0-9_] ,您可以使用\\w

所以myString.matches("\\\\w*") .matches必须匹配整个字符串,所以不需要^\\\\w*$ .find可以匹配一个子字符串)

https://docs.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html

100% 字母数字 RegEx(它仅包含字母数字,甚至不包含整数和字符,仅包含字母数字)

例如:

特殊字符(不允许)
123(不允许)
asdf(不允许)
1235asdf(允许)


String name="^[^<a-zA-Z>]\\d*[a-zA-Z][a-zA-Z\\d]*$";

如果您还想包含外语字母,您可以尝试:

String string = "hippopotamus";
if (string.matches("^[\\p{L}0-9']+$")){
    string is alphanumeric do something here...
}

或者,如果您想允许特定的特殊字符,但不允许其他任何字符。 例如对于#space ,您可以尝试:

String string = "#somehashtag";
if(string.matches("^[\\p{L}0-9'#]+$")){
    string is alphanumeric plus #, do something here...
}

要检查字符串是否为字母数字,您可以使用遍历字符串中每个字符并检查它是否为字母数字的方法。

    public static boolean isAlphaNumeric(String s){
            for(int i = 0; i < s.length(); i++){
                    char c = s.charAt(i);
                    if(!Character.isDigit(c) && !Character.isLetter(c))
                            return false;
            }
            return true;
    }

暂无
暂无

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

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