2019-01-09 16:21
浏览 248


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


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

图片转代码服务由CSDN问答提供 功能建议

我有一个字符串,该字符串可能带有-name,后跟值(可以有空格),也可能有 -descr后跟一个值(-descr后跟一个值,可能也可能不存在):


  runcmd -name abcd xyz -descr abc def 


  runcmd -name abcd xyz 
 <  / code>  

使用Go语言,我该如何编写regexp,如果存在-descr,它将返回给我字符串。 因此,对于上述两个示例,结果应为:

  runcmd -name abcd xyz 



但是,那没有返回任何匹配。 我想知道正确的正则表达式来获取直到-descr的字符串

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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


    runcmd -name...-descr abc def
    点赞 评论
  • douqujin2767 2019-01-09 16:31

    By "Does not work", do you mean it doesn't match anything, or just not what you expect?

    https://regex101.com/ is generally very helpful when testing regular expressions.

    I do not believe there's a simple way to achieve what you want. Things become a lot simpler if we can assume the text betweeen -name and -descr doesn't contain any - in which case, regex.MustCompile(`-name ([^-]*)`) should work

    With this kind of thing, often it's easier and clearer to use 2 regular expressions. So the first strips -descr and anything following it, and the first matches -name and all subsequent characters.

    点赞 评论
  • dqp4933 2019-01-09 17:46

    You are not dealing with a regular language here, so there is no reason to bust out the (slow) regexp engine. The strings package is quite enough:

    package main
    import (
    func main() {
    ", f("runcmd -name abcd xyz -descr abc def"))
    ", f("runcmd -name abcd xyz"))
    ", f("-descr abc def"))
    func f(s string) string {
        if n := strings.Index(s, "-descr"); n >= 0 {
            return strings.TrimRightFunc(s[:n], unicode.IsSpace)
        return s
    // Output:
    // "runcmd -name abcd xyz"
    // "runcmd -name abcd xyz"
    // ""

    Try it on the playground: https://play.golang.org/p/RFC65CYe6mp

    点赞 评论

相关推荐 更多相似问题