duan62819774 2018-08-19 04:16
浏览 21
已采纳

如何在没有给定模式的情况下将字符串拆分为相同的部分?

I have a function that returns every time a different string but with a specific random pattern, this pattern could be as simple as "a, b, c, a, b, c" or something much more complicated.

So what I need is to write a function that searches in the string for a pattern and return it.

There is only one condition to be considered, let's say we have this string for example: "a, b, a, b, c, a, b, a, b, c"

In that string you can't say that "a, b" is a pattern, to consider a specific string as a pattern then it should be longer than the remaining string, in that case, "a,b" is (2 digits * 2) = 4 and the remaining is "c, a, b, a, b, c" 6 digits, so what consider a real pattern is "a, b, a, b, c".

I was about writing a function to do that but I know it's going to be a complicated one so I thought to ask SO before if maybe there is a built-in functionality in PHP or Javascript which can do something close from that or makes the job easier for me, so any ideas guys?

  • 写回答

2条回答 默认 最新

  • dpp89959 2018-08-19 04:52
    关注

    You can do this with a regexp: ^([a-z]{2,})(?:\1)+$. The regex uses a recursive pattern to match any string that has a repeating pattern, placing the pattern in the first group. This is how to use it in PHP:

    Edit

    The regex has been updated to allow an incomplete pattern on the end (as long as there has been one repeat) and then that is checked that it matches for its length against the pattern, to allow matching strings such as abcabca.

    function check_match($string) {
        if (preg_match('/^([a-z]{2,})(?:\1)+(.*)$/', $string, $matches)) {
            return strlen($matches[2]) == 0 || $matches[2] == substr($matches[1], 0, strlen($matches[2])) ? $matches[1] : false;
        }
        return false;
    
    }
    
    foreach (array("abca", "abcabcab", "abcabcabcabc", "ababcababc", "aabbaabb", "aabaab", "aabaabd", "abcd", "aabcaabc", "abcabca") as $str) {
        if ($pattern = check_match($str))
            echo "$str matched $pattern
    ";
        else 
            echo "no pattern for $str
    ";
    }
    

    Output:

    no pattern for abca
    abcabcab matched abc
    abcabcabcabc matched abcabc
    ababcababc matched ababc
    aabbaabb matched aabb
    aabaab matched aab
    no pattern for aabaabd
    no pattern for abcd
    aabcaabc matched aabc
    abcabca matched abc
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)