dongyu2047 2012-08-15 16:08
浏览 49
已采纳

RegEx - 获取未包装的元素数

For example I have a string like this:

first:second:third"test:test":fourth

I want to count the ':' and later to split every ':' to get the strings.

This is my regex:

/(.*):(.*)/iU

I don't know if this is the best solution, but it works. There is a different between a '.' and a "[...] : [...]" so I need to seperate them. I realized that my regex counts the : but continues when the : is between ".

I tried to solve this with this regex:

/(((.*)[^"]):((.*)[^"]))/iU

I thought this is the right way, but it isn't. I tried to learn the regex syntax, but I don't understand this problem.

This regex just means: search for ':' - every think can be infornt and after it EXCEPT wehen a " is in front of it AND a " is after it.

Maybe you can help me.

edit: I use my regex in PHP - maybe this is an important information

  • 写回答

3条回答 默认 最新

  • dtlygweb2017 2012-08-15 16:13
    关注

    How about using

    $result = preg_split(
        '/:       # Match a colon
        (?=       # only if followed by
         (?:      # the following group:
          [^"]*"  #  Any number of characters except ", followed by one "
          [^"]*"  #  twice in a row (to ensure even number of "s)
         )*       # (repeated zero or more times)
         [^"]*    # followed by any number of non-quotes until...
         $        # the end of the string.
        )         # End of lookahead assertion
        /x', 
        $subject);
    

    which will give you the result

    first
    second
    third"test:test"
    fourth
    

    directly?

    This regex splits on a : only if it's followed by an even number of quotes. This means that it won't split on a : inside a string:

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办
  • ¥15 Python爬取指定微博话题下的内容,保存为txt
  • ¥15 vue2登录调用后端接口如何实现
  • ¥65 永磁型步进电机PID算法
  • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?