Search code examples
rstr-replacestringr

How to replace a caret with str_replace from stringr


I have a code problem need some help(exclude specific string).

I found the str_replace_all to do the job.However,it works on other

characters like"/n", "/t" or "A","B","C",except the "^",I want to exclude

this sign but get a error message

(Error in stri_replace_all_regex(string, pattern, fix_replacement(replacement), : Missing closing bracket on a bracket expression.(U_REGEX_MISSING_CLOSE_BRACKET))

Thanks for your help!

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



Solution

  • An option is to wrap with fixed and should be fine

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

    Also, as we are replacing with blank (""), an option is 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 ([^])