【问题标题】:identifying repeating numbers or number patterns in php识别 php 中的重复数字或数字模式
【发布时间】:2015-12-28 18:35:39
【问题描述】:

我在 SO 上看到了很多关于为看起来很疯狂的字符串和东西识别重复模式的问题,但没有任何东西可以捕获重复数字或重复数字模式。

我正在尝试找出一种方法来编写一个可以识别这两种情况的函数。例如,我有一个类似于14285714285714 的数字模式,模式是142857-142857-14。在某些情况下,模式可以是 7575757 : 75-75-75-7。我还有一个重复出现的号码,例如 5555555555555556

如何创建一个函数来确定一个数字是重复的还是有规律的?我想重复的数字可以被视为这种意义上的模式。我对此有点茫然,对此的任何帮助将不胜感激。

提前谢谢你。

编辑如果模式或重新出现的长度超过 3 位,我也只需要抛出 true。

更新 所以我尝试了@stribizhev 推荐与 preg_match 并且确实能够检测到模式。不过,我仍然需要我的模式更加精确。如果我的号码是4444 preg_match 显示我的模式为44-44。我需要能够知道4-4-4-475-75-75 的区别。有人可以帮助我澄清如何从 preg_match 中获得更精确的结果吗?

这是我目前所拥有的。

 $num = 4444;
 if (count($num) >= 3) { 
    $result = preg_match('/(\d+)\1/', $num, $matches);
    if ($result) {
       $repeat = "true";
       echo "match: ".$matches[0].", ".$matches[1]; 
    }
 }

 output: match: 4444, 44

虽然这个输出不是不准确的,但它并不像我需要的那样具体。 44 是模式,但更重要的是 4 是模式。就像在 7575 中一样,75 是模式。

【问题讨论】:

  • 简单的'/(\d+)\1/''/^(?=.*(\d+)\1)/' 怎么样?你能澄清你的编辑吗?
  • 我会用 preg_match 做到这一点吗?
  • 首先你需要清楚你在寻找什么。例如55555555 可以给出5555-555555-55-55-555-5-5-5-5-5-5-5。在这种情况下,您要提取什么模式?
  • 好吧,55555 我需要提取单个数字模式。如果我的号码是 757575,我需要 2 位数字模式。我也用我的 preg_match 尝试更新了我的问题。
  • 为什么5 是单身呢?可能是五十五、五百五十五等。

标签: php regex


【解决方案1】:

这个模式可以完成这项工作:

$pattern = '~
    \A    # start of the string
      # find the largest pattern first in a lookahead
      # (the idea is to compare the size of trailing digits with the smallest pattern)
    (?= (\d+) \1+ (\d*) \z )
      # find the smallest pattern
    (?<pattern> \d+? ) \3+
      # that has the same or less trailing digits
    (?! .+ \2 \z)
      # capture the eventual trailing digits
    (?= (?<trailing> \d* ) )
~x';

if (preg_match($pattern, $num, $m))
    echo 'repeated part: ' . $m[0] . PHP_EOL
       . 'pattern: ' . $m['pattern'] . PHP_EOL
       . 'trailing digits: ' . $m['trailing'] . PHP_EOL;

demo

【讨论】:

  • 这太棒了!谢谢!
猜你喜欢
  • 1970-01-01
  • 2016-05-17
  • 2012-06-21
  • 1970-01-01
  • 2013-11-07
  • 2018-05-04
  • 2015-09-28
  • 2012-05-24
  • 1970-01-01
相关资源
最近更新 更多