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

时间:2015-08-20 14:37:51

标签: regex r gsub grepl

此问题与Stack问题Regular expression parsed with grepl replacement类似。

目标是解析正则表达式并仅替换匹配的模式。例子:

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"

理想的结果会将所有cat替换为chicken

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

知道怎么做到这一点?谢谢你们。

1 个答案:

答案 0 :(得分:1)

使用gsub:

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

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

或者如果您只想要包含cat的那些:

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

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