Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appropriate RegEx for A-Za-z0-9 apostrophe, space, and hyphen with range

Tags:

c#

regex

I need to validate a string using a Regular Expression that can only contain A-Za-z0-9 the apostrophe, space, and hyphen with a range. I've tried doing this in the following method to no avail. What am I doing wrong?

This should validate O'Neil,von-studder, vons studder, and fail if the range is greater than 20 characters or contains characters other than A-Za-z0-9 the apostrophe, space, and hyphen.

public static bool ValidLdapSearchString(string input, int minLength, int maxLength)
{
    try
    {
        string stringValid = @"^[a-zA-Z0-9 " + Regex.Escape("'-") + "]{" + minLength + "," + maxLength + "}";
        Regex regEx = new Regex(stringValid);

        if (!string.IsNullOrEmpty(input) && regEx.IsMatch(input))
        {
            return true;
        }

        return false;
    }
    catch
    {
        throw;
    }
}
like image 502
CodeFunny Avatar asked Dec 19 '25 06:12

CodeFunny


1 Answers

You need a $ or \z anchor at the end and there is no need escaping the symbols you escaped with Regex.Escape:

string stringValid = @"^[a-zA-Z0-9 '-]{" + minLength + "," + maxLength + "}$";

See the .NET regex demo

Note that you do not have to escape the hyphen because it is located at the end of the character class (right before the closing ]). ' is not a special character and does not have to be escaped.

If you need to make sure the string consists of just these symbols and has no trailing newline, use \z anchor instead of $ (that matches either at the end of string or the end of string right before the last \n in the string).

like image 195
Wiktor Stribiżew Avatar answered Dec 20 '25 20:12

Wiktor Stribiżew