tags:

views:

1711

answers:

5

How to validate a string, to only allow alphanumeric characters in it? (regex)

(I don't want to allow for any spaces either).

+8  A: 

Use the expression:

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

ie:

Regex r = new Regex("^[a-zA-Z0-9]*$");
if (r.IsMatch(SomeString)) {
  ...
}
cletus
How about in javascript, same thing I guess?
mrblah
A: 

^\w+$ will allow a-zA-Z0-9_

Use ^[a-zA-Z0-9]+$ to disallow underscore.

Note that both of these require the string not to be empty. Using * instead of + allows empty strings.

Peter Boughton
+1  A: 

replace regex: [^A-Za-z0-9] with: empty string

depending on the language:

in vi: :%s/[^A-Za-z0-9]//g

in php: ereg_replace("[^A-Za-z0-9]", "", $string )

DreadPirateShawn
Based on the tag, that language is C#.
Peter Boughton
+3  A: 

You could do it easily with an extension function rather than a regex ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    for (int i = 0; i < str.Length; i++)
    {
        if (!(char.IsLetter(str[i])) && (!(char.IsNumber(str[i]))))
            return false;
    }

    return true;
}

Per comment :) ...

public static bool IsAlphaNum(this string str)
{
    if (string.IsNullOrEmpty(str))
        return false;

    return (str.ToCharArray().All(c => Char.IsLetter(c) || Char.IsNumber(c)));
}
JP Alioto
It may be a matter of taste, but I would express the loop as "foreach (char c in str) {...}". Whether an empty string is to be considered as OK depends on the application, so I would take this out. I also wouldn't pad 6 empty lines into such a trivial routine, but I guess that's C#/Java/C++ style -- the coders seem to be paid by screen real estate. Anyway, this is the right direction, so +1.
Svante
I'd think we'd want to use IsDigit in this situation, rather than IsNumber -- IsNumber will return true for digits, or for things that *look* like numbers (fractions, Roman numerals, etc.; see http://msdn.microsoft.com/en-us/library/yk2b3t2y.aspx). Given that, and if one was feeling particularly evil, one could compress the contents of IsAlphaNum even further: return string.IsNullOrEmpty(str) ? false : str.ToCharArray().All(Char.IsLetterOrDigit);
stack
A: 

While I think the regex-based solution is probably the way I'd go, I'd be tempted to encapsulate this in a type.

public class AlphaNumericString
{
    public AlphaNumericString(string s)
    {
        Regex r = new Regex("^[a-zA-Z0-9]*$");
        if (r.IsMatch(s))
        {
            value = s;                
        }
        else
        {
            throw new ArgumentException("Only alphanumeric characters may be used");
        }
    }

    private string value;
    static public implicit operator string(AlphaNumericString s)
    {
        return s.value;
    }
}

Now, when you need a validated string, you can have the method signature require an AlphaNumericString, and know that if you get one, it is valid (apart from nulls). If someone attempts to pass in a non-validated string, it will generate a compiler error.

You can get fancier and implement all of the equality operators, or an explicit cast to AlphaNumericString from plain ol' string, if you care.

kyoryu