2

我想用新字符串替换正则表达式匹配的字符串,但仍保留部分原始文本。

我想得到

I own_VERB it and also have_VERB it

I own it and also have it

我如何用一行代码做到这一点?我试过了,但不能比这更进一步。谢谢,

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
      }
4

3 回答 3

3

您甚至不需要捕获组。

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}包含匹配整个模式的字符串;${1}将包含与第一个子模式(或捕获组)匹配的字符串(如果有),您可以在 Darka 的答案中看到。

于 2013-10-01T16:57:01.190 回答
1

在替换内部,$符号被解释为 Expand,例如 $1 代表第一个子匹配的文本。

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"))      
}

输出

I own_VERB it and also have_VERB it
于 2013-10-01T16:32:15.230 回答
1

似乎有点谷歌搜索有帮助:

var validID = regexp.MustCompile(`(own|have)`)
return validID. ReplaceAllString(str, "${1}_VERB")
于 2013-10-01T16:38:01.430 回答