severaltipsaboutregularexpressions
1.processfor"greedy"
bydefault,thequantifiersare"greedy",thatis,they
matchasmuchaspossible(uptothemaximumnumberofper-
mittedtimes),withoutcausingtherestofthepatternto
fail.theclassicexampleofwherethisgivesproblemsisin
tryingtomatchcommentsincprograms.theseappearbetween
thesequences/*and*/andwithinthesequence,individual
*and/charactersmayappear.anattempttomatchccom-
mentsbyapplyingthepattern
/\*.*\*/
tothestring
/*firstcommand*/notcomment/*secondcomment*/
fails,becauseitmatchestheentirestringduetothe
greedinessofthe.*item.
however,ifaquantifierisfollowedbyaquestionmark,
thenitceasestobegreedy,andinsteadmatchestheminimum
numberoftimespossible,sothepattern
/\*.*?\*/
小结:
?与/u有类似功能,但同时出现彼此抵消
如下:
$a="asdf/*asdfaldsfasdf*/asfdasldf;kfldsj*/asfddsaf";
$pattern="/\/\*.*?\*\//";
//$pattern="/\/\*.*\*\//u";
//$pattern="/\/\*.*?\*\//u";
preg_match($pattern,$a,$match);
print_r($match);
?>
2.assertions
\w+(?=;)
matchesawordfollowedbyasemicolon,butdoesnotinclude
thesemicoloninthematch,and
foo(?!bar)
matchesanyoccurrenceof"foo"thatisnotfollowedby
"bar".notethattheapparentlysimilarpattern
小结:
(?!)只前向判断匹配,如bar(?!foo),而(?!foo)bar没有意义
(?