如何匹配字符串中的1个字符

时间:2013-07-12 07:11:11

标签: java regex string character match

我正在为密码策略编写代码。

政策说你不能拥有你已经使用过的同一封信。 例如:密码 - 你不能使用密码因为它有两个'

我该怎么做?

编辑:

这是我的全面实施:

private static final String PASSWORD_DUPLICATE_CHARACTERS = "^(?:([a-zA-Z])(?!.*\\1))$";

pattern = Pattern.compile(PASSWORD_DUPLICATE_CHARACTERS);
this.checkForDuplicateLetters(LDAPNewUserPassword);

private boolean checkForDuplicateLetters(final String newPassword) throws LDAPException{
    LoggingEnt userEnt = new LoggingEnt();
    String userid = userEnt.getUseridCode();
    boolean foundDuplicate = false;

    matcher = pattern.matcher(newPassword);

    if (newPassword.matches(PASSWORD_DUPLICATE_LETTERS)){
        foundDuplicate = true;
        userEnt.setMsg1("Duplicate.");
        throw new LDAPException("Invalid password combination for " + userid, LDAPException.INVALID_CREDENTIALS);//BAristo
    } else {
        userEnt.setMsg1("Your password has been successfully changed.");
    }

    return matcher.matches();

}

3 个答案:

答案 0 :(得分:1)

使用此正则表达式:

private static final String PASSWORD_PATTERN_LOWER_8 = "^(?:([a-zA-Z])(?!.*\\1))$";

答案 1 :(得分:0)

您可以按如下方式使用negative lookahead assertion

<snip> PASSWORD_PATTERN_LOWER_8 = "(?i)^(?!.*(.).*\\1)";

<强>解释

(?i)  # Case-insensitive mode
^     # Match start of string (might be redundant, but won't hurt either)
(?!   # Assert that it's impossible to match...
 .*   # any string
 (.)  # that's followed by one character (captured into group 1)
 .*   # followed by any string
 \\1  # and a repetition of the character we captured before.
)     # End of lookahead

性能不会那么好,特别是对于较长的字符串,因为在最坏的情况下,每个角色都必须与其他角色进行比较。

例如,密码.qwertzuiopasdfghjklöäyxcvbnm,.只会在超过1000步的正则表达式引擎后被检测为无效,而qwertzuiopasdfghjklöäyxcvbnm,..会立即失败。

首先对字符串进行排序并直接查找后续字符可能是个更好的主意:

<snip> PASSWORD_PATTERN_LOWER_8 = "(?i)^(?!.*(.)\\1)";

答案 2 :(得分:0)

我会用这样的东西

^((.)(?!.*\1))+$

这将匹配字符串

中任何位置没有重复字符的字符串