我有一个客户要求,在选择密码时,用户不能在密码字符串中使用超过三个连续的字符或数字。例如:
abc ->> allowed
abcd ->> not allowed
wxy ->> allowed
wxyz ->> not allowed
stu ->> allowed
stuv ->> not allowed
并且具体为ab,bc,kl,op这些是允许的。我的意思是连续数字或字符最长为3。并且不允许任何超过三个长度(连续)的东西。像12345,123456,456789,abcdef,pqrstuv - 这些是不允许的。
同样适用于数字。示例:
123 ->> allowed
1234 ->> not allowed
456 ->> allowed
4567 ->> not allowed
345 ->> allowed
3456 ->> not allowed
和12,45,78,89允许这些。
正则表达式是否可以实现?如果是这样,那么需要一点帮助。
我尝试过以下正则表达式:
^(?:(?!(?:abcd|bcde|cdef|defg|efgh|fghi|ghij|hijk|ijkl|jklm|klmn|lmno|mnop|nopq|opqr|pqrs|qrst|rstu|stuv|tuvw|uvwx|vwxy|wxyz|(a|b|c|d|e|f|g|h|i|j|k|l|m|n|o|p|q|r|s|t|u|v|w|x|y|z)\1{3})).)*
但是这个正则表达式没有给出正确的输出。就像它找到了字符串“abc”和“acm”的匹配。
为了测试我的正则表达式,我使用以下正则表达式测试器:
答案 0 :(得分:1)
我认为这种事情最好用代码而不是正则表达式来完成。我只是使用Character.isLetter(c)并将你的字符转换为整数以查看它们是否按顺序排列。
答案 1 :(得分:1)
这是一个快速,肮脏,非优化(可能是错误的)但又包含你自己想要实现的内容的例子。
public static void main(String[] args) {
// should not allow
System.out.println(hasValidSequence("abcd", 3));
// should not allow
System.out.println(hasValidSequence("1234", 3));
// should allow
System.out.println(hasValidSequence("abcd", 4));
// should allow
System.out.println(hasValidSequence("1234", 4));
}
public static boolean hasValidSequence(String input, int maxAllowed) {
// boilerplate validation of empties/nulls
if (input == null || input.isEmpty()) {
// TODO handle better?
return false;
}
// counter for blowing things up if reached
int counter = 0;
// char takes int values - initializing as bogus 0
char c = (char)0;
// iterating input String characters one by one
for (int i = 0; i < input.length(); i++) {
// previous char is next char as int, - 1 --> they're successive
// you can fool around and replace with input.charAt(i) <= i
// for indirect sequences or same characters
// TODO check it's an alpha numeric!
if (c == input.charAt(i) - 1) {
// incrementing counter
counter++;
}
// assigning current char
c = input.charAt(i);
// counter reached? we blow things up!
if (counter == maxAllowed) {
return false;
}
}
// no counter reached, return true
return true;
}
<强>输出强>
false
false
true
true