如何在r中替换字符串中的确切模式?

时间:2014-06-16 10:35:32

标签: r gsub

我有这个文字。

raw <- "this is Mapof ttMapof qwqqwMApofRt Mapofssdsd it"

我希望输出为:

"this is Mapof (Map of) ttMapof (Map of) qwqqwMapofRt Mapof (Map of)ssdsd it"

所以,你看,我想用“Mapof(Map of)”替换每个“Mapof”,而不是“qwqqwMapofRt”中的那个。

我该怎么做?

1 个答案:

答案 0 :(得分:4)

您需要指定&#34; Mapof&#34;应该使用\b结束这个词:

> raw <- "this is Mapof ttMapof qwqqwMapofRt it"
> gsub("Mapof\\b", "Mapof (Map of)", raw)
[1] "this is Mapof (Map of) ttMapof (Map of) qwqqwMapofRt it"

来自?regex

  

符号\ b匹配单词边缘

的空字符串

编辑:如果您希望字符串匹配单词的结尾或单词的开头,则正则表达式变为:

> raw <- "this is Mapof ttMapof qwqqwMapofRt Mapofssdsd it"
> gsub("Mapof\\b|\\bMapof", "Mapof (Map of)", raw)
[1] "this is Mapof (Map of) ttMapof (Map of) qwqqwMapofRt Mapof (Map of)ssdsd it"

Mapof\\b表示字符串应与单词\\bMapof的结尾匹配,它应与开头匹配。两者都以|分隔,表示OR

相关问题