doumao8803 2018-10-05 16:14
浏览 377
已采纳

按空格将字符串拆分为数组,除非对part进行了引号(golang例外)

Currently, I have the following code:

cmd := "echo \"Hello world\"!\x00"
re := regexp.MustCompile(`[^\s"']+|"([^"]*)"|'([^']*)`)
args := re.FindAllString(cmd, -1)
fmt.Println("%v", args)

This yields the array %v [echo "Hello world" !], but I want the output to be %v [echo "Hello world"!] (basically, quotes should contain everything inside of them as one item in the array, but the terminating quote should not signal the immediate start of the next item in the array).

How would I go about doing this?

  • 写回答

2条回答 默认 最新

  • douxian1923 2018-10-05 19:07
    关注

    You are explicitly matching ", then any number of ^", then ", so of course it terminates after the second ". If you were to wrap that with [^\s"']* (matching anything but whitespace and ") in a grouping, I think it may give you what you are looking for. Let me know if this result is satisfactory.

    re := regexp.MustCompile(`[^\s"']+|([^\s"']*"([^"]*)"[^\s"']*)+|'([^']*)`)
    

    Playground example: https://play.golang.org/p/fWWsx7dIIRd

    I'm not super well versed as to regular expression efficiency, so pardon if this adds too much complexity to the expression.

    EDIT: One caveat to this specific expression is that a single " will break something into two results, e.g. hi"there would split into hi and there.

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

报告相同问题?

悬赏问题

  • ¥15 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭