首页 > 解决方案 > 如何用 stringr 中的 str_replace 替换插入符号

问题描述

我有一个代码问题需要一些帮助(排除特定字符串)。

我找到了str_replace_all做这项工作。但是,它适用于其他

“/n”、“/t”或“A”、“B”、“C”等字符,除了“^”,我想排除

此标志但收到错误消息

(stri_replace_all_regex 中的错误(字符串,模式,fix_replacement(替换),:括号表达式上缺少右括号。(U_REGEX_MISSING_CLOSE_BRACKET))

谢谢你的帮助!

code=c("^GSPC","^FTSE","000001.SS","^HSI","^FCHI","^KS11","^TWII","^GDAXI","^STI")
str_replace_all(code, "([^])", "")


标签: rstr-replacestringr

解决方案


一个选项是包装fixed并且应该没问题

library(stringr)
str_replace_all(code, fixed("^"), "")
#[1] "GSPC"      "FTSE"      "000001.SS" "HSI"       "FCHI"      "KS11"      "TWII"      "GDAXI"     "STI"  

此外,当我们用空白 ( "") 替换时,一个选项是str_remove

str_remove(code, fixed("^"))

Regarding why the OP's code didn't, inside the square brackets, if we use ^, it is not reading the literal character, instead the metacharacter in it looks for characters other than and here it is blank ([^])


推荐阅读