49

Possible Duplicate:
Regular Expression for alphanumeric and underscores

How to create a regex for accepting only alphanumeric characters?

Thanks.

Community
  • 1
  • 1
MarkJ
  • 543
  • 2
  • 5
  • 9

6 Answers6

110

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
  • 1,969
  • 13
  • 26
niksvp
  • 5,475
  • 2
  • 23
  • 40
  • 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
  • 28,996
  • 10
  • 68
  • 104
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
  • 313,408
  • 56
  • 485
  • 544
4

try with \w

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

Torres
  • 5,180
  • 4
  • 24
  • 26
3

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

See here for more info.

Community
  • 1
  • 1
ace
  • 6,687
  • 7
  • 37
  • 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
  • 1,969
  • 13
  • 26