2012-01-27 14 views
1

"*"または "?"の使用に違いはありますか? PHPのpreg_match?または例がありますか? *?試合が固定されていないので、あなたは違いを見分けることができないあなたの特定のテストの文脈では"*"と "?"の違いは何ですか? PHP pregの試合で?

<?php 

// the string to match against 
$string = 'The cat sat on the matthew'; 

// matches the letter "a" followed by zero or more "t" characters 
echo preg_match("/at*/", $string); 

// matches the letter "a" followed by a "t" character that may or may not be present 
echo preg_match("/at?/", $string); 
+13

コメントであなたのコードはすでに違いを記述しています。 –

+0

@GregHewgill preg_matchでは、関数は最初の一致の後に停止するので、両方ともですか? *は最初の一致の後で正確に同じポイントで停止し、 "1"を返します。違いはなんですか ? – motto

+2

@GregHewgillのようなものですが、なぜなら、この場合、2つが同じように動作する理由を説明していないことを除いて。 – Alnitak

答えて

6

*試合0以上

?試合0または1

かそれに続くものはありません。を含む文字列と、それに続くtのいずれかの文字列と一致します。あなたとのに対し

echo preg_match("/at*z/", "attz"); // true 
echo preg_match("/at?z/", "attz"); // false - too many "t"s 

:あなたは後マッチ文字、例えば何かを持っていた場合

違いは重要

echo preg_match("/at*/", "attz"); // true - 0 or more 
echo preg_match("/at?/", "attz"); // true - but it stopped after the 
            // first "t" and ignored the second 
+0

特に質問にはありませんが、購入はいくつかの混乱につながる可能性があります忘れないでください? '。*?'のような非貪欲な演算子として。 –

+0

@JonathanKuhn確かに、その文脈では修飾子であり、それ自体はマッチ演算子ではありません。 – Alnitak

+0

「?」に複数の用途があることを示しています。後で誰かが '。*? 'を見た場合、彼らは1つの文字、0以上、0または1を意味すると考えると混乱するかもしれません。 –

3
// matches the letter "a" followed by zero or more "t" characters 

// matches the letter "a" followed by a "t" character that may or may not be present 

ソース:You

+2

私はあなたの答えを親指で押さえなければなりません... :) –

関連する問題