开发者

Create one RegEx to validate a username

I wrote this code to validate a username meets the given conditions, does anyone see how I can conbine the 2 RegExs into one? Code is c#

    /// <summary>
    /// Determines whether the username meets conditions.
    /// Username conditions:
    /// Must be 1 to 24 character in length
    /// Must start with letter a-zA-Z
    /// May contain letters, numbers or '.','-' or '_'
    /// Must not end in '.','-','._' or '-_' 
    /// </summary>
    /// <param name="userName">proposed username</param>
    /// <returns>True if the username is valid</returns>
    private static Regex sUserNameAllowedRegEx = new Regex(@"^[a-zA-Z]{1}[a-zA-Z0-9\._\-]{0,23}[^.-]$", RegexOptions.Compiled);
    private static Regex sUserNameIllegalEndingRegEx = new Regex(@"(\.|\-|\._|\-_)$", RegexOptions.Compiled);
    public static bool IsUserNameAllowed(string userName)
开发者_运维知识库    {
        if (string.IsNullOrEmpty(userName)
            || !sUserNameAllowedRegEx.IsMatch(userName)
            || sUserNameIllegalEndingRegEx.IsMatch(userName)
            || ProfanityFilter.IsOffensive(userName))
        {
            return false;
        }
        return true;
    }


If I understand your requirements correctly, the below should be what you want. The \w matches letters, digits, or _.

The negative lookbehind (the (?<![-.]) part) allows _ unless the preceding character was . or -.

@"^(?=[a-zA-Z])[-\w.]{0,23}([a-zA-Z\d]|(?<![-.])_)$"


Try adding a greedy + on the last character class and make the middle class non-greedy:

@"^[a-zA-Z][a-zA-Z0-9\._\-]{0,22}?[a-zA-Z0-9]{0,2}$"

this will disallow anything ending in any combination of ., -, or _. This isn't exactly what you have in your original regex, but I figure it's probably what you're going for.


^[a-zA-Z][a-zA-Z0-9._-]{0,21}([-.][^_]|[^-.]{2})$

This is really getting close (it meets all your requirements except that it requires at least three characters, rather than just one). Getting down to one would require some research on my part into C#'s regex capabilities, and I don't have time right now but I hope this gets you going in the right direction.


Friend, you have only four expressions to verify at the end of the string, right? So use the first regex to validate username and then check those four endings by using String functions. It won't consume much more time processing than a freaking regular expression.

Try the method string.EndsWith() to verify for '.', '-', '.' or '-'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜