drbvm26000 2012-01-17 12:36
浏览 35
已采纳

PCRE:使用PHP捕获可选模式

I have a string from which I need to capture one and possibly two substrings (using PHP):

  • The first one is mandatory
  • The second one is optional
  • The first and second ones are separated by unknown junk
  • The second one may or may not be followed by more junk I don't care about

I am unable to make my pattern capture the second pattern unless I make it mandatory in the pattern string. This makes the pattern fail when only the first pattern is available in the subject.

I'm stumped. This shouldn't be that hard.

<?php

// sometimes the subject looks like this:
//$subject = 'pattern 111 -then some random junk-';
$subject = 'pattern 111 -then some random junk- pattern 222';

preg_match('/(pattern 111)(.*?)(pattern 222)?/', $subject, $matches);

print_r($matches);

?>

This is what I get from the above:

Array
(
    [0] => pattern 111
    [1] => pattern 111
    [2] => 
)

Seems to boil down to how do I make {0,1} (that is, the final ? operator in the pattern) be more greedy (ironic given that as a quantifier modifier it does the opposite)

  • 写回答

1条回答 默认 最新

  • douzhe1264 2012-01-17 12:41
    关注

    Try this here

    (pattern 111)(?:.*(pattern 222))?
    

    See it here on Regexr

    I made the second group a non capturing one, so you do have two capturing groups, the first one contains the mandatory part and the second one would contain the optional part.

    It will not work to combine the lazy quantifier with an optional part at the end, but if the optional part is missing, there is no need to match the part following your mandatory pattern, so just include the unknown junk into the optional part.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据