【问题标题】:Replace all words in a sentence starting with dollar signs替换以美元符号开头的句子中的所有单词
【发布时间】:2021-12-27 08:31:20
【问题描述】:

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

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_allstartsWith 试过了。
但到目前为止,我还没有找到解决方案。
对于使用 tidyverse 包的建议解决方案,我也会非常高兴。

【问题讨论】:

    标签: r regex string


    【解决方案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"
    

    【讨论】:

    • OP 编辑​​后,我们需要 + 而不是 *。
    • 感谢您提供此解决方案。我忘记了只有美元符号后面的字母才应该被处理。见编辑。
    【解决方案2】:

    使用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"
    

    【讨论】:

    • 另一个问题:如何替换用户标签:my_string&lt;- "Hi, how are you @user1" 解决方案应该是:"Hi, how are you usertag"
    • @TobKel 将 $ 替换为 @。
    • 不,它不起作用。这是因为@符号后面也跟着小写字母和数字。
    • @TobKel 当然不行,我们需要小写字母。 "\\@[a-z]+"
    猜你喜欢
    • 2015-01-11
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2012-07-10
    相关资源
    最近更新 更多