51

Possible Duplicate:
Regular Expression for alphanumeric and underscores

How to create a regex for accepting only alphanumeric characters?

Thanks.

Community
  • 1
  • 1
MarkJ
  • 563
  • 2
  • 5
  • 9

6 Answers6

112

Try below Alphanumeric regex

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

^ - Start of string

[a-zA-Z0-9]* - multiple characters to include

$ - End of string

See more: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

pintxo
  • 2,085
  • 14
  • 27
niksvp
  • 5,545
  • 2
  • 24
  • 41
  • 1
    This will also match an EMPTY string, which may not be desirable in most situations. To counter that simply replace the trailing `*` with `+` So basically it's `^[a-zA-Z0-9]+$` to avoid false positives generated by empty strings. You can also text your regex at https://regex101.com/ – Ivan Jun 03 '20 at 09:12
28

[a-zA-Z0-9] will only match ASCII characters, it won't match

String target = new String("A" + "\u00ea" + "\u00f1" +
                             "\u00fc" + "C");

If you also want to match unicode characters:

String pat = "^[\\p{L}0-9]*$";
Frank Schmitt
  • 30,195
  • 12
  • 73
  • 107
18

Only ASCII or are other characters allowed too?

^\w*$

restricts (in Java) to ASCII letters/digits und underscore,

^[\pL\pN\p{Pc}]*$

also allows international characters/digits and "connecting punctuation".

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561
4

try with \w

http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html

Torres
  • 5,330
  • 4
  • 26
  • 26
3

Use this ^[a-zA-Z0-9_]*$

See here for more info.

Community
  • 1
  • 1
ace
  • 6,775
  • 7
  • 38
  • 47
2

see http://download.oracle.com/javase/1.5.0/docs/api/java/util/regex/Pattern.html

for example [A-Za-z0-9]

pintxo
  • 2,085
  • 14
  • 27