正则表达式

风行水上 @ 2011-06-20 22:03:03
标签:

    正则表达式是文字匹配时很有用的工具。

    分组

    可以给匹配到的分组起个名字,比如:

    (?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d)
    

    如果在PHP中的话,匹配成功后可以通过名字访问匹配变量:

    preg_match(/(?P<year>\d\d\d\d)-(?P<month>\d\d)-(?P<day>\d\d)/', $text, $matches);
    
    echo $matches['year'], $matches['month'], $matches['day'];
    

    注释

    正则表达式中也可以包含注释,其语法形如 (?#comment)

    以匹配时间为例 (\d\d\d\d)(?#year)-(\d\d){?#month)-(\d\d)(?#day),year、month、day分别注释了三个匹配的部分。

    利用正则表达式的注释,可以作为被匹配的部分的变量名。当然这需要一些处理。

    参考资源

    标签:

      分享到:
      comments powered by Disqus

      26/29ms