正则表达式检测字符是否重复超过三次

dav*_*307 5 java regex kotlin

我尝试遵循此处描述的解决方案:https ://stackoverflow.com/a/17973873/2149915 尝试匹配具有以下要求的字符串: - 应匹配并返回字符串中按顺序重复的超过 3 个字符。

例子:

  • 你好,你好吗... -> 有效
  • 你好,你好吗............ -> 无效
  • hiii -> 有效
  • hiiiiii -> 无效

等等,这个想法是检测无意义的文本。

到目前为止,我的解决方案是修改链接中的正则表达式。

原来的:^(?!.*([A-Za-z0-9])\1{2})(?=.*[a-z])(?=.*\d)[A-Za-z0-9]+$

改编:^(?!.*([A-Za-z0-9\.\,\/\|\\])\1{3})$

本质上,我删除了捕获此处看到的数字和字母数字组的要求:(?=.*[a-z])(?=.*\d)[A-Za-z0-9]+并尝试添加额外的字符检测,例如./,\等,但它似乎根本不与任何字符匹配......

关于如何实现这一目标有什么想法吗?

提前致谢 :)

编辑:我找到了这个正则表达式:^.*(\S)(?: ?\1){9,}.*$关于这个问题/sf/answers/3126135001/并将其调整为仅匹配 3 个字符,例如这样^.*(\S)(?: ?\1){3}.*$

现在它检测到以下内容:

  • aaaa -> 无效
  • 你好.... -> 无效
  • /////.... -> 无效

但是它没有考虑空白,例如:

  • . . . . .

是否可以进行修改来实现此目的?

Men*_*ena 3

我认为如果您正在寻找重复超过 3 次的任何字符,有一个更简单的解决方案:

String[] inputs = {
    "hello how are you...", // -> VALID
    "hello how are you.............", // -> INVALID
    "hiii", // -> VALID
    "hiiiiii" // -> INVALID
};
//                            | group 1 - any character
//                            | | back-reference
//                            | |   | 4+ quantifier including previous instance
//                            | |   |     | dot represents any character, 
//                            | |   |     | including whitespace and line feeds
//                            | |   |     | 
Pattern p = Pattern.compile("(.)\\1{3,}", Pattern.DOTALL);
// iterating test inputs
for (String s: inputs) {
    // matching
    Matcher m = p.matcher(s);
    // 4+ repeated character found
    if (m.find()) {
        System.out.printf(
            "Input '%s' not valid, character '%s' repeated more than 3 times%n", 
            s, 
            m.group(1)
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

Input 'hello how are you............. not valid', character '.' repeated more than 3 times
Input 'hiiiiii' not valid, character 'i' repeated more than 3 times
Input 'hello    how are you' not valid, character ' ' repeated more than 3 times
Run Code Online (Sandbox Code Playgroud)