【问题标题】:RegEx expression to validate the input string用于验证输入字符串的正则表达式
【发布时间】:2009-07-14 11:27:31
【问题描述】:

我正在寻找一个正则表达式来验证输入,该输入应包含以下四个字符组中的至少三个:

English uppercase characters (A through Z)
English lowercase characters (a through z)
Numerals (0 through 9)
Non-alphabetic characters (such as !, $, #, %)

提前致谢。

编辑:这是针对 .NET Framework 的

【问题讨论】:

  • @Brian 刚刚编辑了问题以包含您的答案

标签: regex


【解决方案1】:

不是在一个正则表达式中,但认为这是一种方式:

int matchedGroupCount = 0;
matchedGroupCount += Regex.IsMatch(input, "[a-z]") ? 1 : 0;
matchedGroupCount += Regex.IsMatch(input, "[A-Z]") ? 1 : 0;
matchedGroupCount += Regex.IsMatch(input, "[0-9]") ? 1 : 0;
matchedGroupCount += Regex.IsMatch(input, "[!*#%, etc..]") ? 1 : 0;

if (matchedGroupCount >= 3)
   pass
else
   failed

【讨论】:

  • 猜你应该使用matchedGroupCount >= 3 而不是等号。
【解决方案2】:

老实说,我想不出直接的方法来做到这一点:正则表达式不太支持“必须包含”。你用什么语言写这个?就个人而言,我会通过依次检查每个正则表达式并计算你得到多少匹配来做到这一点,所以在 python 中它会是这样的:

#!/usr/bin/python
import re
count = 0
mystring = "password"
regexp = re.compile(r'[A-Z]')
if regexp.search(mystring) is not None:
    count += 1
regexp = re.compile(r'[a-z]')
if regexp.search(mystring) is not None:
    count += 1
# etc
if count < 3:
    print "Not enough character types"

你也可以更简洁地做到这一点:

#!/usr/bin/python
import re
regexpArray = [re.compile(r'[A-Z]'), re.compile(r'[a-z]'), re.compile(r'\d'), re.compile(r'[^A-Za-z0-9]')]
count = 0
for regexp in regexpArray:
    if regexp.search(mystring) is not None:
        count += 1
if count < 3:
    print "Not enough character types"

或者,您可以有一个非常复杂的正则表达式,其中包含许多选项(以不同的顺序)或您可以通过 google 找到的各种密码强度检查器之一。

编辑

不使用正则表达式的 python 方法如下所示。我确信有一个 .NET 等价物,它比正则表达式匹配要快得多。

#!/usr/bin/python
import string

mystring = "password"
count = 0
for CharacterSet in [string.ascii_lowercase, string.ascii_uppercase, "0123456789", r'''!"£$%^&*()_+-=[]{};:'@#~,<.>/?\|''']:
    # The following line adds 1 to count if there are any instances of
    # any of the characters in CharacterSet present in mystring
    count += 1 in [c in mystring for c in CharacterSet]
if count < 3:
    print "Not enough character types"

可能有更好的方法来生成符号列表。

【讨论】:

  • 如果在 Python 中,我会建议 str.isalpha(), len(password)==3, str.isdigit() 而不是使用 re.
  • 我试图记住一些好的“过滤”风格的做法,但请注意,如果有任何非字母数字字符,isalpha() 将返回 False,这不是这里需要的.需要的是类似“如果 mystring 中有 ['a', 'b', ...] 中的任何一个”:count += 1”。
  • 我添加了一个替代正则表达式的替代方法。
猜你喜欢
  • 2016-08-23
  • 2014-12-03
  • 1970-01-01
  • 2013-02-09
  • 2018-10-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多