繁体   English   中英

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

[英]How do I replace an exact pattern in a string in r?

我有这段文字。

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”中的那个。

我该怎么做?

您需要指定“ Mapof”应该以\\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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM