I want to replace all elements of a string starting with a dollar sign. Here you can find my example:
my_string <- "$AAPL $TSLA I recomend to buy $TLSA and to sell $AAPL; the price is rising to $12.56"
The replacement is the word "cashtag"
.
Here is my desired output:
my_string
"cashtag cashtag I recomend to buy cashtag and to sell cashtag; the price is rising to $12.56"
I already tried it with str_replace_all
and startsWith
.
But so far I have not come to a solution.
I would also be very happy about a suggested solution using the tidyverse package.
CodePudding user response:
note than in a regex in R, you'll have to escape the $
with a backslash, and then you'll have to escape this backslash with another backslash ;)
stringr::str_replace_all(my_string, "\\$[A-Z] ", "cashtag")
[1] "cashtag cashtag I recomend to buy cashtag and to sell cashtag; the price is rising to $12.56"
CodePudding user response:
Using gsub:
gsub("\\$[A-Z] ", "cashtag", my_string)
# [1] "cashtag cashtag I recomend to buy cashtag and to sell cashtag; the price is rising to $12.56"