+ -
当前位置:首页 → 问答吧 → 请教正则匹配的问题(?:(?:as_)?q|cha|p)=([^\&]+)

请教正则匹配的问题(?:(?:as_)?q|cha|p)=([^\&]+)

时间:2011-10-01

来源:互联网

(?:(?:as_)?q|cha|p)=([^\&]+)

请问(?:(?:as_)?q|cha|p)这段怎么理解?

以下是我做的实验,和输出的结果:
preg_match('![\&\?](?:(?:as_)?q|cha|p)=([^\&]+)!i', '&as_q=123', $match_1);

print_r($match_1);
  1. Array ( [0] => &as_q=123 [1] => 123 )
复制代码
preg_match('![\&\?](?:(?:as_)?q|cha|p)=([^\&]+)!i', '&as_cha=123', $match_1);

print_r($match_1);
  1. Array ( )
复制代码
为什么&as_q=123可以匹配到, 但是&as_cha=123不行? 请问(?:(?:as_)?q|cha|p)这段怎么理解?

多谢

作者: andis01   发布时间: 2011-10-01

  1. <?php
  2. $parrent = '/[\&\?](?:(?:as_)?(?:q|cha|p))=([^\&]+)/i';
  3. $str = '&as_q=123&as_cha=123';
  4. preg_match_all($parrent, $str, $matches);
  5. // 返回 Array ( [0] => Array ( [0] => &as_q=123 [1] => &as_cha=123 ) [1] => Array ( [0] => 123 [1] => 123 ) )
  6. print_r($matches);
  7. ?>
复制代码


q|cha|p是属于as_之后的一个选择子集,所以他们是一个权重一样的集合,即(?:q|cha|p),若不这样写,则是以他们之间的 “|”为第一级的多重选择了。
另外(?:as_)?表示(?:as_)是可有可无的,建议将?去掉,这样应该更严谨。

作者: loho   发布时间: 2011-10-02

相关阅读 更多