dqkmn26444 2019-01-09 16:21
浏览 279
已采纳

Golang正则表达式匹配字符串,直到给定的字符序列

I have a string that could have a -name followed by value (that can have spaces) and there could also be -descr after that followed by a value (the -descr followed by value may nor may not be there):

Example strings:

runcmd -name abcd xyz -descr abc def

or

runcmd -name abcd xyz

With Go language, how do I write regexp, that returns me the string before -descr if it exists. so, for both examples above, the result should be:

runcmd -name abcd xyz

I was trying:

regexp.MustCompile(`(-name ).+?=-descr`)

But, that did not return any match. I wanted to know the correct regexp to get the string up until -descr if it exists

  • 写回答

3条回答 默认 最新

  • douchun1900 2019-01-09 16:40
    关注

    You could capturin first part with -name in a group, then match what is in between and use an optional second capturing group to match -descr and what follows.

    Then you could use the capturing groups when creating the desired result.

    ^(.*? -name\b).*?(-descr\b.*)?$
    

    Regex demo | Go demo

    For example:

    s := "runcmd -name abcd xyz -descr abc def"
    re1 := regexp.MustCompile(`^(.*? -name\b).*?(-descr\b.*)?$`)
    result := re1.FindStringSubmatch(s)
    fmt.Printf(result[1] + "..." + result[2])
    

    Result:

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

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!