正则表达式检查重复字符



我需要使用正则表达式检查5位数字。检查条件:1。重复数字不应超过2个(类型为11234)。2. 不应该有12345或54321序列。我想做的是:var PASSWORD_PATTERN = "^(?=[\\D]*\\d)(?!.*(\\d)\\1)(?!.*\\2{3,}){5,}.*$",但是检查12345或54321不起作用。

可以断言不是3个相同的数字,也可以断言不是12345和54321。

注意Java\d中的反斜杠要进行双转义。

^(?!d*(d)d*1d*1)(?!12345)(?!54321)d{5}$

模式匹配:

  • ^字符串起始
  • (?!d*(d)d*1d*1)负向前看,不匹配3次相同的数字使用2个反向引用1
  • (?!12345)Assert not 12345
  • (?!54321)Assert not 54322
  • d{5}匹配5位数字
  • $字符串结束

Regex演示

如果字符串不包含5个数字,则立即匹配失败,如果所有断言都成功,则匹配1+数字。

^(?=d{5}$)(?!d*(d)d*1d*1)(?!12345)(?!54321)d+$

Regex演示

如果你不想匹配0-9的升序和降序序列,你可以手动检查每个硬编码序列的字符串,或者生成序列并将它们添加到列表中。

然后您可以检查5位数字的序列是否在列表中,并从模式中删除带有遍历的精确检查。

List<String> sequences = new ArrayList<>();
for (int i = 0; i < 10; i++) {
StringBuilder sequence = new StringBuilder();
int last = i;
for (int j = 0; j < 5; j++) {
++last;
if (last > 9) last = 0;
sequence.append(last);
}
sequences.add(sequence.toString());
sequences.add(sequence.reverse().toString());
}
String[] strings = {"12345", "54321", "34567", "90123", "112341", "12356", "00132"};
for (String s : strings) {
if ((!sequences.contains(s)) && s.matches("^(?=\d{5}$)(?!\d*(\d)\d*\1\d*\1)\d+$")) {
System.out.printf("%s is not a sequence and does not contain 3 of the same digitsn", s);
}
}

输出
12356 is not a sequence and does not contain 3 of the same digits
00132 is not a sequence and does not contain 3 of the same digits

Java演示

最新更新