Create one RegEx to verify username

I wrote this code to verify that the username meets the given conditions, and does anyone see how I can combine 2 RegExs into one? Code - 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;
    }
+4
source share
4 answers

If I understand your requirements correctly, below should be what you want. \wmatches letters, numbers or _.

negative lookbehind (part (?<![-.])) allows _if the previous character was not .or -.

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

Try adding greedy +to the last character class and make the middle class inanimate:

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

, ., - _. , , , , , , .

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

( , , , ). #, , , .

+1

Friend, you only have four expressions to check at the end of the line, right? Therefore, use the first regular expression to validate the username, and then test these four endings with the String functions. It will not consume much more processing time than freaking regular expression.

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

+1
source

All Articles