62

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

Johannes Jander
  • 4,974
  • 2
  • 31
  • 46
O__O
  • 950
  • 1
  • 9
  • 17
  • 2
    Try this: /^[a-z0-9]+$/i Check [here][1] too [1]: http://stackoverflow.com/questions/388996/regex-for-javascript-to-allow-only-alphanumeric – Vimalnath Jun 28 '12 at 09:34

12 Answers12

91

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

caffreyd
  • 1,151
  • 1
  • 17
  • 25
Raghav
  • 4,590
  • 1
  • 22
  • 32
  • 8
    -1 as this doesn't cover all alphanumberic characters. M42's response is better. – tster Jan 14 '13 at 22:41
  • 9
    Poor use of `if`, better would be `return s.matches(pattern)` – Fr4nz May 12 '15 at 11:48
  • 2
    * allow empty string , use + , like this : ^[a-zA-Z0-9]+$ – Adnan Abdollah Zaki Dec 14 '15 at 16:00
  • 1
    Do you really need to add the boundary matchers (^,$) at the beginning and end? It seems like `String pattern="[a-zA-Z0-9]+";` would behave the same way since + is greedy. – krick Jun 29 '17 at 21:08
  • Need regex to check if string not contain "test" and contain only alphabet and space. please help – shiva Sep 11 '18 at 07:03
  • @krick Yes, you do need the anchors `^, $` for validation regex. Try testing this string `abc@def` at some site like https://regex101.com/ and you'll see why. You are right that `+` is greedy, but that means it will match `abc` and `def` instead of `a`, `b`, `c`, `d`, `e`, `f` which a lazy `+?` would. Note: [Java's String.matches() will automatically add the `^,$` anchors](https://stackoverflow.com/questions/1894624/is-regex-in-java-anchored-by-default-with-both-a-and-character) if you don't have them, but it's probably a good practice to include them. – wisbucky Nov 07 '18 at 00:35
27

In order to be unicode compatible:

^[\pL\pN]+$

where

\pL stands for any letter
\pN stands for any number
Toto
  • 89,455
  • 62
  • 89
  • 125
  • Not working. Giving: java.util.regex.PatternSyntaxException: Incorrect Unicode property near index 5. – Abdalrahman Shatou Sep 13 '16 at 09:13
  • IntelliJ also suggests `\\p{Alnum}` (but that's in Java 13) – Erk Jun 01 '20 at 03:31
  • @Erk I believe that has been around since Java 7: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html – slugmandrew Jan 05 '21 at 15:53
  • @slugmandrew, good to know. I was hedging. Seems there is one as far back as java 6. But not java 5—it doesn't even seem to have a Pattern class. – Erk Jan 07 '21 at 03:52
  • Works in Java May 2023. It's the most concise answer, yet still readable. (IntelliJ doesn't suggest change.) – devdanke May 05 '23 at 18:41
17

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.

Johannes Jander
  • 4,974
  • 2
  • 31
  • 46
11

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}]+$".

ewan.chalmers
  • 16,145
  • 43
  • 60
5

Use character classes:

^[[:alnum:]]*$
Igor Chubin
  • 61,765
  • 13
  • 122
  • 144
  • 4
    This is the right idea, but [POSIX character class syntax](http://en.wikipedia.org/wiki/Regular_expression#Character_classes) is [not valid in Java](http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html), and the question is tagged as Java. The equivalent Java syntax for your answer is `"^[\\p{Alnum}]*$"`, as mentioned [below](http://stackoverflow.com/a/11241830/1840078). (If such tagging is not considered to be sufficiently conspicuous by site guidelines, let me know and I'll add a comment to the question itself. :)) – Mark A. Fitzgerald May 07 '14 at 15:56
4
Pattern pattern = Pattern.compile("^[a-zA-Z0-9]*$");
Matcher matcher = pattern.matcher("Teststring123");
if(matcher.matches()) {
     // yay! alphanumeric!
}
Seth Malaki
  • 4,436
  • 23
  • 48
1

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()) {

}
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
1

To consider all Unicode letters and digits, Character.isLetterOrDigit can be used. In Java 8, this can be combined with String#codePoints and IntStream#allMatch.

boolean alphanumeric = str.codePoints().allMatch(Character::isLetterOrDigit);
Unmitigated
  • 76,500
  • 11
  • 62
  • 80
1

To include [a-zA-Z0-9_], you can use \w.

So myString.matches("\\w*"). (.matches must match the entire string so ^\\w*$ is not needed. .find can match a substring)

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

Curtis Yallop
  • 6,696
  • 3
  • 46
  • 36
-1

100% alphanumeric RegEx (it contains only alphanumeric, not even integers & characters, only alphanumeric)

For example:

special char (not allowed)
123 (not allowed)
asdf (not allowed)
1235asdf (allowed)


String name="^[^<a-zA-Z>]\\d*[a-zA-Z][a-zA-Z\\d]*$";
Emma
  • 27,428
  • 11
  • 44
  • 69
Amit
  • 9
-1

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...
}
Emma
  • 27,428
  • 11
  • 44
  • 69
BrianG7
  • 155
  • 1
  • 4
-4

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;
    }