views:

3662

answers:

3

I need to find a reg ex that only allows alphanumeric. So far, everyone I try only works if the string is alphanumeric, meaning contains both a letter and a number. I just want one what would allow either and not require both.

Thanks!

+2  A: 
^\s*([0-9a-zA-Z]*)\s*$

or, if you want a minimum of one character:

^\s*([0-9a-zA-Z]+)\s*$

Square brackets indicate a set of characters. ^ is start of input. $ is end of input (or newline, depending on your options). \s is whitespace.

The whitespace before and after is optional.

The parentheses are the grouping operator to allow you to extract the information you want.

EDIT: removed my erroneous use of the \w character set.

cletus
-1 because \w matches underscore
Greg
+11  A: 
/^[a-z0-9]+$/i

^         start of string
[a-z0-9]  a or b or c or ... z or 0 or 1 or ... 9
+         one or more times (change to * to allow empty string
$         end of string

/i        case-insensitive
Greg
And that's the magic right there!
FluidFoundation
A: 

Use the character class. The following is equilavent to a "^[a-zA-Z0-9]+$":

^\w+$

Explanation:

  • ^ start
  • \w any work character (A-Z, a-z, 0-9).
  • $ end

Edit: \w matches one additional character, the underscore.

Chase Seibert
\w is actually equivalent to [a-zA-Z_0-9] so your RegEx also matches underscores [_].
Martin Brown