关于php正则表达式的两点备注

2016-02-19 16:48 3 1 收藏

下面图老师小编要向大家介绍下关于php正则表达式的两点备注,看起来复杂实则是简单的,掌握好技巧就OK,喜欢就赶紧收藏起来吧!

【 tulaoshi.com - Web开发 】

  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*/

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/webkaifa/)

  fails,becauseitmatchestheentirestringduetothe

  greedinessofthe.*item.

  However,ifaquantifierisfollowedbyaquestionmark,

(本文来源于图老师网站,更多请访问https://www.tulaoshi.com/webkaifa/)

  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没有意义

  (?

来源:https://www.tulaoshi.com/n/20160219/1613185.html

延伸阅读
标签: Web开发
正则表达式是一种文本模式,包括普通字符(例如,a 到 z 之间的字母)和特殊字符(称为元字符)。模式描述在搜索文本时要匹配的一个或多个字符串。   正则表达式示例 表达式 匹配 /^\s*$/ 匹配空行。 /\d{2}-\d{5}/ 验证由两位数字、一个连字符再加 5 位数字组成的 ID 号。 /\s*(\S+)(\s[^]*)?[\s\S]*\s*\/\1\s*/ ...
标签: Web开发
正则表达式在PHP中被用来处理复杂的文字串。支持正则表达式的函数有: ereg()ereg replace()eregi replace()split() 这些函数都将正则表达式作为他们的第一个参数。PHP使用POSIX扩展规则表达式(使用POSIX 1003.2)。要找到所有的关于POSIX扩展规则表达式的描述,请查看包括在PHP发行版本之内的regex man页面。 Examp...
正则表达式简介 翻译:NorthTibet 原文出处:Regular Expressions 有些新手对正则表达式不是很熟悉,有必要在此作一简单回顾。如果你是正则表达式高手,可以不用看这一部分。 正则表达式是描述字符串集的字符串。例如,正则表达式“Mic*”描述所有包含“Mic”,后跟零个或多个字符的字符串。Mickey、Microsoft、Michelangelo...
标签: Web开发
在PHP中有两套正则表达式函数库,两者功能相似,只是执行效率略有差异: 一套是由PCRE(Perl Compatible Regular Expression)库提供的。使用“preg_”为前缀命名的函数; 一套由POSIX(Portable Operating System Interface of Unix )扩展提供的(PHP默认)。使用以“ereg_”为前缀命名的函数; PHP中,正则表达式有三个作用: 匹配,也常...
标签: Web开发
最后写了一个IP地址的正则表达式验证程序。 代码如下: ((25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(25[0-5]|2[0-4]\d|1?\d?\d) 截图如下:

经验教程

62

收藏

40
微博分享 QQ分享 QQ空间 手机页面 收藏网站 回到头部