我想用新字符串替换正则表达式匹配的字符串,但仍保留原始文本的一部分。我想得到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 回答
倚天杖
TA贡献1828条经验 获得超3个赞
似乎有点谷歌搜索帮助:
var validID = regexp.MustCompile(`(own|have)`)
return validID. ReplaceAllString(str, "${1}_VERB")
aluckdog
TA贡献1847条经验 获得超7个赞
在替换内部,$符号被解释为在 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
- 3 回答
- 0 关注
- 350 浏览
添加回答
举报
0/150
提交
取消