doujie4344 2015-02-06 14:05
浏览 58
已采纳

将正则表达式捕获组合并为1个数组?

In PHP I have the following regex to match words that are between [] or {} :

\[([^\]]*)\]|\{([^\}]*)\}

When using this on this text :

xyz[word1]abc[word2]def{word4}ghi[word5]jkl{word6}mno

with

preg_match_all('/\[([^\]]*)\]|\{([^\}]*)\}/i', 'xyz[word1]abc[word2]def{word4}ghi[word5]jkl{word6}mno', $result);

I get an array that contains 3 arrays, with the 2 different capture groups as 2 different arrays.

The regex is a simple example to illustrate the question, so simplyfying the regex to use only 1 capture group is not an option. I must have 2 different capture groups but need them only in 1 result array.

So, is there any way to combine multiple capture groups into 1 capture-result array ?

  • 写回答

1条回答 默认 最新

  • douzi7711 2015-02-06 14:07
    关注

    Use the branch reset group (?|.....) to turn multiple captures into a single one.

    (?|\[([^\]]*)\]|\{([^\}]*)\})
    

    That is, alternatives inside a branch reset group share the same capturing groups.

    DEMO

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

报告相同问题?

悬赏问题

  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题
  • ¥15 目标检测项目无法读取视频
  • ¥15 GEO datasets中基因芯片数据仅仅提供了normalized signal如何进行差异分析
  • ¥100 求采集电商背景音乐的方法