Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/video/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用stringr查找和替换字符串_R_Regex_Stringr_Stringi - Fatal编程技术网

使用stringr查找和替换字符串

使用stringr查找和替换字符串,r,regex,stringr,stringi,R,Regex,Stringr,Stringi,我试图找到并替换由字符串组成的数据帧的一些值。简单的例子如下: library(stringr) test1 <- c("one", "two", "three") str_replace_all(string = test1, pattern = c('one' = "1ne", 'three' = "3ree")) > [1] "1ne" "two" "3ree" 然而,像下面这样一个更

我试图找到并替换由字符串组成的数据帧的一些值。简单的例子如下:

library(stringr)
test1 <- c("one", "two", "three")
str_replace_all(string = test1,
                pattern = c('one' = "1ne",
                            'three' = "3ree"))
> [1] "1ne"  "two"  "3ree"
然而,像下面这样一个更复杂的案例是行不通的。我做错了什么

test2 <- c("one (1) x1", "two (2) x2", "three (3) x3")
test2 <- c("one (1) x1", "two (2) x2", "three (3) x3")
str_replace_all(string = test2,
                   pattern = c('one (1) x1' = "X1",
                               'two (2) x2' = "X2"))
> [1] "one (1) x1"   "two (2) x2"   "three (3) x3"

使用fixed避免正则表达式匹配

str_replace_all(string = test2,
                pattern = fixed(c('one (1) x1' = "X1",
                          'two (2) x2' = "X2")))
# [1] "X1"           "X2"           "three (3) x3"

在模式中使用大括号之前,请尝试使用“\\”,例如一个\\1\\x1str\u替换\u所有使用正则表达式和圆括号都不会被解释为圆括号。在正则表达式中,圆括号有特殊含义。您需要对其进行转义或使用fixed。可能重复