如果你有有限的字符序列之後彼此您可以在輸入上匹配使用Pattern
,.find()
,只是反轉測試:
// Only the alternation is needed, no need for the capture
private static final Pattern PATTERN
= Pattern.compile("012|123|234|345|456|567|678|789|890");
// ...
if (PATTERN.matcher(input).find())
// fail: illegal sequence found
但是,如果你想檢測代碼點一個跟着一個,你必須使用字符函數:
final CharBuffer buf = CharBuffer.wrap(input);
int maxSuccessive = 0;
int successive = 0;
char prev = buf.get();
char next;
while (buf.hasRemaining()) {
next = buf.get();
if (next - prev == 1)
successive++;
else {
maxSuccessive = Math.max(maxSuccessive, successive);
successive = 0;
}
prev = next;
}
// test maxSuccessive
不過請注意,這將按照「規範有序」,不覈對測試連續的字符。例如,在某些語言環境中,a
之後立即是A
,而不是b
。
更一般地,如果你想測試密碼要求和約束的演變,你最好稍微分割一下。例如,考慮一下:
public interface PasswordChecker
{
boolean isValid(final String passwd);
}
爲每個檢查實現此接口(例如,長度,存在/不存在的某些字符等),當你做檢查密碼,有List
的跳棋;密碼是無效的,如果一個檢查返回false:
private final List<PasswordChecker> checkers = ...;
// then
for (final PasswordChecker checker: checkers)
if (!checker.isValid(passwd))
return false;
return true;
如果使用番石榴,你可以忘掉PasswordChecker
和使用Predicate<String>
。
來源
2013-07-18 05:56:21
fge
正則表達式總是處理字符串。他們不知道字符的含義,例如他們不知道2是多於1 – stema
請將您的代碼與未匹配的字符串以及應用正則表達式的位置一起發佈。 – stema