duanju8308 2015-11-04 00:20
浏览 54

正则表达式验证带有字母数字但没有相同字符的字符串

I am working on a regex to validate a string that,

  • contains alphanumeric value
  • does not contain identical characters more than 4 times in a row (like aaaaa or 222222)
  • total length should be between 6 to 15

I am using the following regex, but it doesn't work for the input => String1bbbbb

/^(?=.*[a-z])(?=\S*[A-Z])(?=\S*[0-9])(?!.*[\w{4,}])[a-zA-Z0-9]{6,15}+$/i


if(preg_match('/^(?=.*[a-z])(?=\S*[A-Z])(?=\S*[0-9])(?!.*[\w{4,}])[a-zA-Z0-9]{6,15}+$/i', $string)) {
    echo "Valid String";
} else {
    echo "invalid String";
}

using negative look ahead to validate the identical characters like below

(?!.*[\w{4,}])

Any help would be appreciated.

  • 写回答

1条回答 默认 最新

  • dop20345 2015-11-04 00:34
    关注

    You can use this regex:

    ^(?=.{6,15}$)(?:([A-Za-z0-9])\1{0,3}(?!\1))+$

    This will make sure length is between 6 and 15, it will capture the character, possibly repeated up to 3 more times and then it will make sure the same character does not get repeated again in the next position. Here you have it in regex101: https://regex101.com/r/aO7pM5/1

    评论

报告相同问题?

悬赏问题

  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源