Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for checking if a string is strictly alphanumeric

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

like image 389
O__O Avatar asked Jun 28 '12 09:06

O__O


3 Answers

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

like image 56
Raghav Avatar answered Oct 21 '22 16:10

Raghav


In order to be unicode compatible:

^[\pL\pN]+$

where

\pL stands for any letter
\pN stands for any number
like image 22
Toto Avatar answered Oct 21 '22 17:10

Toto


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.

like image 17
Johannes Jander Avatar answered Oct 21 '22 17:10

Johannes Jander