正则表达式表示字母数字、至少 1 个数字和特殊字符
本文关键字:数字 特殊字符 至少 表示 正则表达式 | 更新日期: 2023-09-27 18:36:18
我正在尝试找到一个正则表达式,它将给我以下验证:
字符串应至少包含 1 位数字和至少 1 个特殊字符。允许字母数字。
我尝试了以下方法,但失败了:
@"^[a-zA-Z0-9@#$%&*+'-_(),+':;?.,!'[']'s''/]+$]"
我尝试了"password1$",但失败了我也尝试了"密码1!",但也失败了。
想法?
更新需要解决方案才能使用 C# - 目前截至 2013 年 10 月 22 日发布的建议似乎不起作用。
试试这个:
Regex rxPassword = new Regex( @"
^ # start-of-line, followed by
[a-zA-Z0-9!@#]+ # a sequence of one or more characters drawn from the set consisting of ASCII letters, digits or the punctuation characters ! @ and #
(<=[0-9]) # at least one of which is a decimal digit
(<=[!@#]) # at least one of which is one of the special characters
(<=[a-zA-Z]) # at least one of which is an upper- or lower-case letter
$ # followed by end-of-line
" , RegexOptions.IgnorePatternWhitespace ) ;
构造(<=regular-expression)
是一个零宽度正后视断言。
一步地做事要简单得多。静态构造函数从允许的特殊字符的简单列表中生成转义字符类字符。内置的 Regex.Escape
方法在这里不起作用。
public static class PasswordValidator {
private const string ALLOWED_SPECIAL_CHARS = @"@#$%&*+_()':;?.,![]'-";
private static string ESCAPED_SPECIAL_CHARS;
static PasswordValidator() {
var escapedChars = new List<char>();
foreach (char c in ALLOWED_SPECIAL_CHARS) {
if (c == '[' || c == ']' || c == '''' || c == '-')
escapedChars.AddRange(new[] { '''', c });
else
escapedChars.Add(c);
}
ESCAPED_SPECIAL_CHARS = new string(escapedChars.ToArray());
}
public static bool IsValidPassword(string input) {
// Length requirement?
if (input.Length < 8) return false;
// First just check for a digit
if (!Regex.IsMatch(input, @"'d")) return false;
// Then check for special character
if (!Regex.IsMatch(input, "[" + ESCAPED_SPECIAL_CHARS + "]")) return false;
// Require a letter?
if (!Regex.IsMatch(input, "[a-zA-Z]")) return false;
// DON'T allow anything else:
if (Regex.IsMatch(input, @"[^a-zA-Z'd" + ESCAPED_SPECIAL_CHARS + "]")) return false;
return true;
}
}
这可能是工作,有两种可能,特殊字符之前的数字或特殊字符之后的数字。你应该使用DOTALL(点点所有字符)
^((.*?[0-9].*?[@#$%&*+'-_(),+':;?.,!'[']'s''/].*)|(.*?[@#$%&*+'-_(),+':;?.,!'[']'s''/].*?[0-9].*))$
这对我有用:
@"(?=^[!@#$%''^&*()_-+=[{]};:<>|./?a-zA-Z''d]{8,}$)(?=([!@#$%''^&*()_-+=[{]};:<>|./?a-zA-Z''d]''W+){1,})(?=[^0-9][0-9])[!@#$%''^&*()_-+=[{]};:<>|./?a-zA-Z''d]*$"
字母数字、至少 1 个数字和最小长度为 8 的特殊字符
这应该可以完成工作
(?:(?=.*[0-9]+)(?=.*[a-zA-Z]+)(?=.*[@#$%&*+'-_(),+':;?.,!'[']'s''/]+))+
用javascript测试,不确定c#,可能需要一些小的调整。
它的作用是使用预期的积极展望来查找密码的必需元素。
编辑
正则表达式旨在测试是否存在匹配项。由于所有模式都是前瞻的,因此不会捕获任何实际字符并且匹配为空,但如果表达式"match",则密码有效。
但是,由于问题是 C#(对不起,我不知道 C#,只是即兴创作和改编示例)
string input = "password1!";
string pattern = @"^(?:(?=.*[0-9]+)(?=.*[a-zA-Z]+)(?=.*[@#$%&*+'-_(),+':;?.,!'[']'s''/]+))+.*$";
Regex rgx = new Regex(pattern, RegexOptions.None);
MatchCollection matches = rgx.Matches(input);
if (matches.Count > 0) {
Console.WriteLine("{0} ({1} matches):", input, matches.Count);
foreach (Match match in matches)
Console.WriteLine(" " + match.Value);
}
添加行首和结尾的.*$
,如果密码有效,表达式将匹配。匹配值将是密码。(我猜)