使用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。可能重复