1

我有一个这样的字符串:

str1 <- "get all securities in portfolio port1 on date 2010-12-31 where field value of Close on 2010-12-31+10 less than 2000"

我正在尝试将“2010-12-31+10”转换为str1. 我尝试str_replace_allstringr打包的方法但我没有得到输出。

> str_replace_all(str1,"2010-12-31+10","2011-01-10")
[1] "get all securities in portfolio port1 on date 2010-12-31 where field value of Close on 2010-12-31+10 less than 2000"

这是什么原因?

4

1 回答 1

3

的第二个参数str_replace_all不是字符串而是正则表达式。因此,您必须转义诸如+在 regexps 中具有特殊含义的符号:

R> str_replace_all(str1,"2010-12-31\\+10","2011-01-10")
[1] "get all securities in portfolio port1 on date 2010-12-31 where field value of Close on 2011-01-10 less than 2000"

或者您可以使用 的fixed 功能stringr使其与您的模式匹配为常规字符串:

R> str_replace_all(str1,fixed("2010-12-31+10"),"2011-01-10")
[1] "get all securities in portfolio port1 on date 2010-12-31 where field value of Close on 2011-01-10 less than 2000"
于 2013-10-04T09:17:08.587 回答