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

时间:2013-10-01 16:26:29

标签: regex go

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

我想要

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
      }

3 个答案:

答案 0 :(得分:2)

您甚至不需要捕获组。

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的答案中看到。

答案 1 :(得分: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

答案 2 :(得分:1)

似乎有点谷歌搜索帮助:

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