如何使用R tidyverse替换字符串中以$开头的cashtag标识
基于tidyverse实现cashtag替换方案
核心使用stringr::str_replace_all()配合精准正则表达式即可实现需求,正则规则专门匹配**$后接字母**的cashtag模式,自动避开$后接数字的金额场景。
- 加载依赖(stringr包含在tidyverse生态中)
library(tidyverse)
- 执行替换
这里用到的正则\\$[A-Za-z]+说明:\\$转义匹配美元符号本身,[A-Za-z]+匹配1个及以上的大小写字母,刚好命中你需要替换的cashtag规则。
my_string <- "$AAPL $TSLA I recomend to buy $TLSA and to sell $AAPL; the price is rising to $12.56" result <- str_replace_all(my_string, pattern = "\\$[A-Za-z]+", replacement = "cashtag")
- 输出结果验证
print(result) # 输出: "cashtag cashtag I recomend to buy cashtag and to sell cashtag; the price is rising to $12.56"
如果你的cashtag存在字母加数字的组合(比如$AAPL123),只需要把正则调整为\\$[A-Za-z][A-Za-z0-9]*即可,依然会自动过滤$开头后接数字的金额内容。
内容的提问来源于stack exchange,提问作者TobKel
相关产品推荐
相关产品推荐

