找到包含至少 5 个和最多 6 个点的子字符串

find the sub-string that contains at least 5 and at most 6 dots

Info : sub-strings are separated by spaces within the string.

Mission : find the sub-string that contains at least 5 and at most 6 dots.

Catch : there is no specific order to the dots that are mixed within the sub-strings.

在下面的示例中.. 输出应该是.. "d...d..d" 因为它是第一个满足 "at least 5 dots and at most 6 dots" 条件的匹配项。

$string = "a.a.a b.b..b c..c..c d...d..d e.e";
$pattern = "_not_known_";
preg_match($pattern, $string, $matches);
echo $matches[0];
echo "/n";

期望的输出:

d...d..d

如果您的答案不需要正则表达式,那么您就可以了。

$string = "a.a.a b.b..b c..c..c d...d..d e.e.....";
$string = explode(' ', $string); //Split a string by space
$result = null;

for ($i=0; $i < count($string); $i++) {
    $dots = substr_count($string[$i], '.'); //Count dot in string
    if ($dots == 5 || $dots ==6 ) {
        $result = $string[$i];
        break;
    }
}

var_dump($result);

代码:(Demo) (Pattern Demo)

$string = "a.a.a b.b..b c....c....c d...d..d e.e";

echo preg_match('~(?<=^|\s)([a-z])(?:\.?){5,6}(?=$|\s)~', $string, $match) ? $match[0] : 'no match';

输出:

d...d..d

模式分解:

~                 # pattern's starting delimiter
(?<=^|\s)         # lookbehind to ensure that match is preceded by no characters or a whitespace
([a-z])           # capture a single letter as "capture group #1"
(?:\.?){5,6}    # match a single dot, then optionally the same letter from capture group #1; repeat ONLY 5 or 6 times
                # match the letter from capture group #1 to ensure that the sequence ends how it starts
(?=$|\s)          # lookahead to ensure that match is followed by no characters or a whitespace
~                 # pattern's ending delimiter