2

not^演算子を後方参照と組み合わせて使用​​する場合、なぜ遅延一致を使用する必要があるのですか? not試合を中断する必要があるようです。

例えば:

<?php
preg_match('/(t)[^\1]*\1/', 'is this test ok', $matches);
echo $matches[0];
?>

this test真ん中が一致しないthis tにも関わらずではなく を出力します。を一致させるために使用する必要があります。t[^\1]/(t)[^\1]*?\1/this t

さらに

preg_match('/t[^t]*t/', 'is this test ok', $matches);

一致するのみthis tです。

何が起こっているのか、私は何を誤解していますか?

4

2 に答える 2

5

\1here は文字クラス内の後方参照ではないため、機能しません。は\1ASCII 値 1 の文字として解釈されます。

代わりに否定的なルックアラウンドを使用して、必要な効果を得ることができます。

'/(t)(?:(?!\1).)*\1/'
于 2010-08-25T23:58:56.673 に答える
2

You cannot use backreferences inside character classes. [^\1] means "any character other than 1".

Instead, use /(t)(?:(?!\1).)*\1/.

(?:...) is a non-capturing group

(?!...) is a "negative look-ahead", asserting that the subexpression doesn't match

(?!\1)., when \1 is a single character, means "any character that does not match \1

于 2010-08-25T23:57:38.657 に答える