正则表达式的例子是什么:字符串不应该包含紧跟在相同序列之后的任何字符序列?

时间:2012-05-04 02:59:01

标签: java regex

在我的程序中,我有一个正则表达式,它确保输入字符串至少有一个alpha和一个数字字符,长度在2到10之间。

Pattern p = Pattern.compile("^(?=.*\\d)(?=.*[A-Za-z])[A-Za-z0-9]{2,10}$");

根据新要求,字符串也不应包含紧跟相同序列的任何字符序列。我搜索了很多,但无法弄清楚。你能帮忙吗?或者指向任何URL /文档?


非常感谢您的回复。

要求:字符串不得包含紧跟相同序列的任何字符序列。

我认为要求不明确。

我不确定“12aardvark”是否有效,因为 - 1.重复“a”。与字符串“11abcdefg”相同。 2.重复“ar” 3.但是“ar”并不是紧跟着相同的序列。中间有“dv”。

我认为,字符串“12ardvark”和“12aardvark”不应该通过验证,因为它具有重复的字符序列:“ar”,尽管它不会立即跟随相同的序列。

“fofo123”或“ab1212”不应该通过,因为“fo”(只有2个字符)后面紧跟着相同的序列。

您对该要求的假设是什么?

1 个答案:

答案 0 :(得分:4)

A monolithic regex is not the answer to every string-validation problem.

使用基本字符串函数和多个较小的正则表达式更具可读性。 (为什么在length(pwd)执行同样的操作时,尝试使用正则表达式来检查字符串的长度?)

这里有一些Python代码应该很好地转换为Java:

import re
def validate_password(pwd):
    # return true if valid or false is invalid.

    if ( len(pwd) < 2 or len(pwd) > 10 ):
        print "Password %s : Failed length requirement" % pwd
        return False
    if ( re.search(r"\d", pwd) == None ):
        print "Password %s : must contain at least one number" % pwd
        return False     
    if ( re.search(r"[a-zA-Z]", pwd) == None ):
        print "Password %s : must contain at least one alphabetical character" % pwd
        return False
    if ( re.search(r"(...+)\1", pwd) != None ):
        print "Password %s : must not contain any repeating substrings of three characters or more" % pwd
        return False

    print "Password %s is OK" % pwd
    return True

test_pwds = [ "1", "123", "aardvark", "12ardvark", "12aardvark", "foofoofoo1" ]

for pwd in test_pwds:
    validate_password (pwd)

测试输出:

Password 1 : Failed length requirement
Password 123 : must contain at least one alphabetical character
Password aardvark : must contain at least one number
Password 12ardvark is OK
Password 12aardvark is OK
Password foofoofoo1 : must not contain any repeating substrings of three characters or more

使用一系列小测试验证输入,而不是一个巨大的测试,有几个好处:

  1. 更容易理解。
  2. 调试起来更容易。
  3. 将来维护起来会更容易。 (想象一下,你的老板增加了另一个要求,密码中必须至少出现两个符号。)
  4. 您可以告诉用户其密码失败的标准,而不是像“您的密码必须符合giant list of criteria”这样的常规消息。