开始,regexp:匹配任意一种情况并保留原始文本

I want to replace regex-matched strings with new string but still keeping part of the original text.

I want to get

I own_VERB it and also have_VERB it

from

I own it and also have it

how do I do this with one line of code? I tried but can't get further than this. Thanks,

http://play.golang.org/p/SruLyf3VK_

      package main

      import "fmt"
      import "regexp"

      func getverb(str string) string {
        var validID = regexp.MustCompile(`(own)|(have)`)
        return validID. ReplaceAllString(str, "_VERB")  
      }

      func main() {
        fmt.Println(getverb("I own it and also have it"))
        // how do I keep the original text like
        // I own_VERB it and also have_VERB it
      }

You don't even need a capture group for this.

package main

import "fmt"
import "regexp"

func getverb(str string) string {
    var validID = regexp.MustCompile(`own|have`)
    return validID. ReplaceAllString(str, "${0}_VERB")  
}

func main() {
    fmt.Println(getverb("I own it and also have it"))
    // how do I keep the original text like
    // I own_VERB it and also have_VERB it
}

${0} contains the string which matched the whole pattern; ${1} will contain the string which matched the first sub-pattern (or capture group) if there is any, and which you can see in Darka's answer.

Inside replacement, $ signs are interpreted as in Expand, so for instance $1 represents the text of the first submatch.

package main

import (
   "fmt"
   "regexp"
)

func main() {
    re := regexp.MustCompile("(own|have)")
    fmt.Println(re.ReplaceAllString("I own it and also have it", "${1}_VERB"))      
}

Output

I own_VERB it and also have_VERB it

Seems a bit googling helps:

var validID = regexp.MustCompile(`(own|have)`)
return validID. ReplaceAllString(str, "${1}_VERB")