【问题标题】:Regex to match three or more of the same char regardless of its position正则表达式匹配三个或更多相同的字符,无论其位置如何
【发布时间】:2019-07-19 04:40:15
【问题描述】:

PHPjavaScript 中寻找一个正则表达式,如果找到 3 个或更多相同字符(无论其“位置”如何),则返回 true:

    "q6dqaqb" -> return true
    "qyakc6m" -> return false
    "jjfffua" -> return true
    "--rr4-c" -> return true
    "-qsev-m" -> return false

我已尽我所能寻找这样的解决方案

(Regular expression: same character 3 times)

但这不符合要求。

编辑:谢谢大家的迅速回复。 PHP 解决方案也很棒。

根据答案,这些正则表达式有什么区别:

(.)(?=.*\1.*\1)

.*(.).*\1.*\1.*

(?=.*(.).*\1.*\1)

对不起,在我明白这意味着什么之前,我无法忍受自己。

【问题讨论】:

  • 所以你的意思是三个相同的字符,即使它们是不连续的? (编辑:如果是这样,有人已经打败了我的答案。)
  • .*(.).*\1.*\1.* 演示:regex101.com/r/G2QtLR/1

标签: javascript php regex


【解决方案1】:

使用前瞻查找三个中的第一个:

/(.)(?=.*\1.*\1)/

【讨论】:

    【解决方案2】:

    这个表情

    (?=.*(.).*\1.*\1)
    

    可能会确保并获得整个字符串,我们可以将其扩展为:

    ^(?=.*(.).*\1.*\1).*$
    

    Demo

    测试

    $re = '/^(?=.*(.).*\1.*\1).*$/m';
    $str = 'q6dqaqb
    qyakc6m
    jjfffua
    --rr4-c
    -qsev-m
    ';
    
    preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0);
    
    var_dump($matches);
    

    输出

    array(3) {
      [0]=>
      array(2) {
        [0]=>
        string(7) "q6dqaqb"
        [1]=>
        string(1) "q"
      }
      [1]=>
      array(2) {
        [0]=>
        string(7) "jjfffua"
        [1]=>
        string(1) "f"
      }
      [2]=>
      array(2) {
        [0]=>
        string(7) "--rr4-c"
        [1]=>
        string(1) "-"
      }
    }
    

    const regex = /^(?=.*(.).*\1.*\1).*$/gm;
    const str = `q6dqaqb
    qyakc6m
    jjfffua
    --rr4-c
    -qsev-m
    `;
    let m;
    
    while ((m = regex.exec(str)) !== null) {
        // This is necessary to avoid infinite loops with zero-width matches
        if (m.index === regex.lastIndex) {
            regex.lastIndex++;
        }
        
        // The result can be accessed through the `m`-variable.
        m.forEach((match, groupIndex) => {
            console.log(`Found match, group ${groupIndex}: ${match}`);
        });
    }

    【讨论】:

      【解决方案3】:

      你可以试试这个/(.).*\1.*\1/

      演示:

      var regex = /(.).*\1.*\1/;
      
      console.log(regex.test("q6dqaqb"))
      console.log(regex.test("qyakc6m"))
      console.log(regex.test("jjfffua"))
      console.log(regex.test("--rr4-c"))
      console.log(regex.test("-qsev-m"))

      【讨论】:

        猜你喜欢
        • 2015-05-14
        • 2021-10-08
        • 2013-12-16
        • 2019-08-25
        • 2014-11-03
        • 2014-05-21
        • 2012-02-11
        • 1970-01-01
        相关资源
        最近更新 更多