doulouxun6756 2013-07-26 16:09
浏览 43
已采纳

php regex:使用引号进行匹配,但不捕获它们

I'm unsure if I should be using preg_match, preg_match_all, or preg_split with delim capture. I'm also unsure of the correct regex.

Given the following:

$string = " ok 'that\\'s cool' \"yeah that's \\\"cool\\\"\"";

I want to get an array with the following elems:

[0] = "ok"
[1] = "that\'s"
[2] = "yeah that's \"cool\""
  • 写回答

3条回答 默认 最新

  • dongzhen4180 2013-07-26 16:14
    关注

    You can not do this with a regular expression because you're trying to parse a non-context-free grammar. Write a parser.

    Outline:

    • read character by character, if you see a \ remember it.
    • if you see a " or ' check if the previous character was \. You now have your delimiting condition.
    • record all the tokens in this manner

    Your desired result set seems to trim spaces, you also lost a couple of the \s, perhaps this is a mistake but it can be important.

    I would expect:

    [0] = " ok " // <-- spaces here
    [1] = "that\\'s cool"
    [2] = " \"yeah that's \\\"cool\\\"\"" // leading space here, and \" remains
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?