Regex for checking if a string is strictly alphanumeric

前端 未结 10 2018
予麋鹿
予麋鹿 2020-12-01 12:02

How can I check if a string contains only numbers and alphabets ie. is alphanumeric?

相关标签:
10条回答
  • 2020-12-01 12:08

    Considering you want to check for ASCII Alphanumeric characters, Try this: "^[a-zA-Z0-9]*$". Use this RegEx in String.matches(Regex), it will return true if the string is alphanumeric, else it will return false.

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

    If it will help, read this for more details about regex: http://www.vogella.com/articles/JavaRegularExpressions/article.html

    0 讨论(0)
  • 2020-12-01 12:08

    See the documentation of Pattern.

    Assuming US-ASCII alphabet (a-z, A-Z), you could use \p{Alnum}.

    A regex to check that a line contains only such characters is "^[\\p{Alnum}]*$".

    That also matches empty string. To exclude empty string: "^[\\p{Alnum}]+$".

    0 讨论(0)
  • 2020-12-01 12:15

    If you want to include foreign language letters as well, you can try:

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

    Or if you wanted to allow a specific special character, but not any others. For example for # or space, you can try:

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

    try this [0-9a-zA-Z]+ for only alpha and num with one char at-least..

    may need modification so test on it

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

    Pattern pattern = Pattern.compile("^[0-9a-zA-Z]+$");
    Matcher matcher = pattern.matcher(phoneNumber);
    if (matcher.matches()) {
    
    }
    
    0 讨论(0)
  • 2020-12-01 12:17

    To check if a String is alphanumeric, you can use a method that goes through every character in the string and checks if it is alphanumeric.

        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;
        }
    
    0 讨论(0)
  • 2020-12-01 12:27

    It's 2016 or later and things have progressed. This matches Unicode alphanumeric strings:

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

    See the reference (section "Classes for Unicode scripts, blocks, categories and binary properties"). There's also this answer that I found helpful.

    0 讨论(0)
提交回复
热议问题