创建一个RegEx以validation用户名

我写了这段代码来validation用户名是否满足给定条件,是否有人看到我如何将2个RegEx合并为一个? 代码是c#

///  /// 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 '-_' ///  /// proposed username /// True if the username is valid 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匹配字母,数字或_

负面的lookbehind ( (?部分)允许_除非前面的字符是.-

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

尝试在最后一个字符类上添加一个贪婪的+并使中间类非贪婪:

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

这将禁止以任何组合结束的任何事情.-_ 。 这不是你在原始正则表达式中所拥有的,但我认为它可能就是你想要的。

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

这真的越来越近了(它满足了你的所有要求,除了它至少需要三个字符,而不是一个)。 一个人需要对C#的正则表达式能力进行一些研究,我现在没有时间,但我希望这能让你朝着正确的方向前进。

朋友,你只有四个表达式要在字符串的末尾validation,对吧? 因此,使用第一个正则表达式validation用户名,然后使用字符串函数检查这四个结尾。 它不会消耗比正常表达式更多的时间。

尝试使用方法string.EndsWith()来validation’。’,’ – ‘,’。 ‘或’ –