替换文本中的字符

时间:2014-04-29 19:47:34

标签: r regex

如何用%2B替换+:

这是我的代码

x<-"asflj + ldjjsf ljsdlafj"
gsub("+","%2B",  x)

我的输出是:

"%2Ba%2Bs%2Bf%2Bl%2Bj%2B %2B+%2B %2Bl%2Bd%2Bj%2Bj%2Bs%2Bf%2B %2Bl%2Bj%2Bs%2Bd%2Bl%2Ba%2Bf%2Bj%2B"

我希望它是"asflj %20 ldjjsf ljsdlafj"

1 个答案:

答案 0 :(得分:3)

+ is a metacharacter然后您可以设置fixed=TRUE跳过它并获得您需要的内容。

> gsub("+","%2B",  x, fixed=TRUE)
[1] "asflj %2B ldjjsf ljsdlafj"

或使用\\+

跳过它
> gsub("\\+","%2B",  x)
[1] "asflj %2B ldjjsf ljsdlafj"