How do you check a string against alphanumerics

  • Thread starter Thread starter Nader
  • Start date Start date
Nader said:
Hi everyone,

In C# how do you verify if a string is alphanumeric?

Thanks for suggestions.
With Regular expressions.. \w+ should be enough to find out if a word is
alphanumeric. If you want the whole sentence.. you will need to write
a little expression. Look up help on Regular expressions to figure out
the complete thing.. Or somebody might help you out here ..
 
Hi,

try
using System.Text.RegularExpressions.*;

bool bIsAlphaNum = Regex.IsMatch (strInput, "^\\w*$");

Replace * with + if you want empty strings to be considered not alpha
numeric.

^ matches begin of string,
\w* matches zero or more consecutive alphanumeric _characters_,
$ matches end of string.

HTH
greetings
 
Thanks a lot for taking the time to reply. As \\w represents alphanumerics
and the underscore character I have to get rid of '_' also. Too bad there is
no built-in function.
 
Hi,

try this expression instead:

bool bIsAlphaNum = Regex.IsMatch (strInput, "^[a-zA-Z0-9]*$");

HTH
greetings
 
Thanks Jhon, you motivated me to get back to Tom Archer's Inside C# to learn
regular expressions. I had skipped that part! :)
 
Back
Top