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;
}
RegEx pattern validation can be added to text input type questions. To add validation, click on the Validation icon on the text input type question.
The username one works perfectly and the password one does too to an extent. This is my program: import uservalidation # get a username from the user username = input("Username: ") # validate username result, reason = uservalidation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With