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 vue3加ant-design-vue无法渲染出页面
  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序