适当的正则表达式用于A-Za-z0-9撇号、空格和带范围的连字符

时间:2023-01-30 21:16:34

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?

我需要使用正则表达式验证一个字符串,该表达式只能包含一个范围内的a- za -z0-9撇号、空格和连字符。我试过用下面的方法做这件事,但没有用。我做错了什么?

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.

如果范围大于20个字符,或者包含A-Za-z0-9以外的字符(撇号、空格和连字符),那么就会失败。

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;
    }
}

1 个解决方案

#1


3  

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

最后你需要一个$或\z锚,没有必要去逃避你用regex逃脱的符号。

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

See the .NET regex demo

参见。net regex演示

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).

如果您需要确保字符串仅由这些符号组成,并且没有拖尾换行,请使用\z锚而不是$(在字符串的最后一个\n之前匹配字符串末尾或字符串末尾)。

#1


3  

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

最后你需要一个$或\z锚,没有必要去逃避你用regex逃脱的符号。

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

See the .NET regex demo

参见。net regex演示

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).

如果您需要确保字符串仅由这些符号组成,并且没有拖尾换行,请使用\z锚而不是$(在字符串的最后一个\n之前匹配字符串末尾或字符串末尾)。