【发布时间】:2021-11-10 22:49:11
【问题描述】:
我对正则表达式很陌生,所以如果这是一个明显愚蠢的问题,我深表歉意。
假设我有一个格式为 (c"fair*", "beaut*") 的字符串,并且我想用开头的插入符号 (^) 替换末尾的星号 (*):c("^公平”,“^美丽”)。我怎么能用 stringr 来做呢?我读过this excellent introduction to regexp,但没有弄清楚。我用 stringr::str_replace_all() 进行了几次尝试,但无济于事。问题似乎是 stringr::str_replace_all() 中的替换不能是正则表达式。是这样吗?如果是,有没有其他方法可以做到这一点?
library(stringr)
x <- c("fair*", "beaut*")
str_replace_all(x, "\\*", "^\\^")
#> [1] "fair^^" "beaut^^"
str_replace_all(x, "\\*", "^\\^")
#> [1] "fair^^" "beaut^^"
str_replace_all(x, "\\*", "\\^*")
#> [1] "fair^*" "beaut^*"
str_replace_all(x, "\\*", "\\^(*)")
#> [1] "fair^(*)" "beaut^(*)"
由reprex package (v2.0.1) 于 2021-09-15 创建
【问题讨论】: