gpt4 book ai didi

c# - 创建一个 RegEx 来验证用户名

转载 作者:太空狗 更新时间:2023-10-30 00:27:50 28 4
gpt4 key购买 nike

我编写这段代码来验证用户名是否满足给定条件,有人看到我如何将 2 个 RegEx 合并为一个吗?代码是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;
}

最佳答案

如果我正确理解您的要求,下面应该是您想要的。 \w匹配字母、数字或 _ .

negative lookbehind ((?<![-.]) 部分)允许 _除非前面的字符是 .- .

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

关于c# - 创建一个 RegEx 来验证用户名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4902749/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com