-2

比如说,给定的字符串是abcwhateverdefwhatever34567whatever012如何匹配那些按顺序排列的组,比如 match abc, def, 34567,012

我现在拥有的正则表达式是(.)\1{2,},但它匹配相同的字符但不是按顺序

4

2 回答 2

1

Here's a solution that solves the problem with regex. It's not very efficient though and I wouldn't recommend it.

from re import findall, X

text = "abcwhateverdefwhatever34567whatever012"

reg = r"""
(?:
(?:0(?=1))|
(?:(?<=0)1)|(?:1(?=2))|
(?:(?<=1)2)|(?:2(?=3))|
(?:(?<=2)3)|(?:3(?=4))|
(?:(?<=3)4)|(?:4(?=5))|
(?:(?<=4)5)|(?:5(?=6))|
(?:(?<=5)6)|(?:6(?=7))|
(?:(?<=6)7)|(?:7(?=8))|
(?:(?<=7)8)|(?:8(?=9))|
(?:(?<=8)9)|

(?:a(?=b))|
(?:(?<=a)b)|(?:b(?=c))|
(?:(?<=b)c)|(?:c(?=d))|
(?:(?<=c)d)|(?:d(?=e))|
(?:(?<=d)e)|(?:e(?=f))|
(?:(?<=e)f)
){1,}
"""

print findall(reg, text, X)

The result is:

['abc', 'def', '34567', '012']

As you can see I only added the numbers and the first 6 letters in the alphabet. It's should be fairly obvious how to continue.

于 2013-08-04T13:17:10.843 回答
1

如果您仍在寻找 PHP 代码。

function getSequence($str) {
    $prev = 0; $next = 0; $length = strlen($str);

    $temp = "";
    for($i = 0; $i < $length; $i++) {
        $next = ord($str[$i]);
        if ($next == $prev + 1) {
            $temp .= $str[$i];
        } else {
            if (strlen($temp) > 1) $result[] = $temp;
            $temp = $str[$i];
        }
        $prev = $next;
    }

    if (strlen($temp) > 1) $result[] = $temp;

    return $result;
}

$str = "abcwhateverdefwhatever34567whatever012";
print_r(getSequence($str));
于 2013-08-04T12:35:51.953 回答