仅替换已解析的正则表达式

Replace only parsed regular expression

这道题类似于堆栈题

objective是解析一个正则表达式,只替换匹配的模式。示例:

data <- c("cat 6kg","cat g250", "dog","cat 10 kg", "no cat") 

解析感兴趣的匹配项 cat:

data[grepl("cat",data)]
[1] "cat 6kg"   "cat g250"  "cat 10 kg" "no cat"

理想的结果是用chicken替换所有出现的cat

[1] "chicken 6kg"   "chicken g250"  "chicken 10 kg" "no chicken"

知道如何实现吗?谢谢大家。

使用 gsub:

gsub("cat", "chicken", data)

[1] "chicken 6kg"   "chicken g250"  "dog"           "chicken 10 kg" "no chicken"

或者如果你只想要包含猫的:

gsub("cat", "chicken", data[grepl("cat",data)])

[1] "chicken 6kg"   "chicken g250"  "chicken 10 kg" "no chicken"