一尘不染

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

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
      }

阅读 251

收藏
2020-07-02

共1个答案

一尘不染

您甚至不需要捕获组。

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

2020-07-02