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条)

报告相同问题?