正则表达式匹配交替字符

Cod*_*ein 1 php regex

我正在尝试匹配一串数字并检测是否存在交替数字的模式。例如,3131是一场比赛。4596961是匹配项,因为它包含9696. 433215不是匹配,因为没有交替数字。

我写的当前表达式是/(\d)(\d)(\\1\\2)+/,它运行良好,除了它也匹配重复的连续数字。例如,它匹配 5555,当我不想要它时,因为 5555 不是由交替数字组成的(至少不是严格地说)。

本质上,我想告诉 Regex 引擎,第一个\d和第二个\d是不同的字符。

我该怎么做呢?

Tim*_*ker 5

使用前瞻断言

/(\d)(?!\1)(\d)(\1\2)+/
Run Code Online (Sandbox Code Playgroud)

此外,如果您使用'...'字符串,您的转义序列只需要一个反斜杠:

if (preg_match(
    '/(\d)  # Match a digit and store it in group number 1
    (?!\1)  # Assert that the next char is not the same as the one in group 1
    (\d)    # Match a digit, store it in group 2
    (\1\2)+ # Match one or more repetitions of the two digits matched previously
    /x', 
    $subject, $regs)) {
    $result = $regs[0];
} 
Run Code Online (Sandbox Code Playgroud)