dongsigan2044 2013-01-02 10:56
浏览 28
已采纳

使用正则表达式拆分字符串

I have this string:

EXAMPLE|abcd|[!PAGE|title]

I want to split it like this:

Array
(
    [0] => EXAMPLE
    [1] => abcd
    [2] => [!PAGE|title]
)

How to do it? Thank you.

  • 写回答

5条回答 默认 最新

  • dongyixiu3110 2013-01-02 11:02
    关注

    DEMO

    If you don't need anything more than you said, is like parsing a CSV but with | as separator and [ as " so: (\[.*?\]+|[^\|]+)(?=\||$) will do the work I think.

    EDIT: Changed the regex, now it accepts strings like [asdf]].[]asf]

    Explanation:

    1. (\[.*?\]+|[^\|]+) -> This one is divided in 2 parts: (will match 1.1 or 1.2)
      1.1 \[.*?\]+ -> Match everything between [ and ]
      1.2 [^\|]+ -> Will match everything that is enclosed by |
    2. (?=\||$) -> This will tell the regular expression that next to that must be a | or the end of the string so that will tell the regex to accept strings like the earlier example.
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?