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 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器