1

我想替换以美元符号开头的字符串的所有元素。在这里你可以找到我的例子:

my_string <- "$AAPL $TSLA I recomend to buy $TLSA and to sell $AAPL; the price is rising to $12.56"

替换是单词"cashtag"
这是我想要的输出:

my_string
"cashtag cashtag I recomend to buy cashtag and to sell cashtag; the price is rising to $12.56"

我已经用str_replace_alland试过了startsWith
但到目前为止,我还没有找到解决方案。
对于使用 tidyverse 包的建议解决方案,我也会感到非常高兴。

4

2 回答 2

1

使用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"
于 2021-11-16T09:03:53.853 回答
1

请注意,与 R 中的正则表达式相比,您必须$用反斜杠转义,然后您必须用另一个反斜杠转义这个反斜杠;)

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"
于 2021-11-16T08:58:33.987 回答