You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R语言中删除字符串指定单词后的内容并保留该单词?

解决方案

可以通过正则匹配实现需求,以下提供两种方法,分别基于stringr包和基础R:

方法一:使用stringr包(推荐,语法更简洁)

首先修正向量定义里的俄文字符,再构建数据框并处理:

# 修正向量定义(将俄文的с替换为英文c)
string <- c("tasty red apple number 1", "tasty red apple and banana", "tasty banana and apple and peach", "tasty banana and peach", "tasty peach and apple")
word <- c("apple", "apple", "apple", "banana", "peach")

# 创建数据框
df <- data.frame(String = string, Word = word, stringsAsFactors = FALSE)

# 安装并加载stringr包(首次使用需执行install.packages("stringr"))
library(stringr)

# 生成After列:提取字符串开头到目标单词(含该单词)的全部内容
df$After <- str_extract(df$String, paste0(".*\\b", df$Word, "\\b"))

# 查看结果
print(df)

方法二:基础R实现(无需额外包)

如果不想依赖第三方包,可使用mapply结合sub函数:

# 修正向量定义并创建数据框
string <- c("tasty red apple number 1", "tasty red apple and banana", "tasty banana and apple and peach", "tasty banana and peach", "tasty peach and apple")
word <- c("apple", "apple", "apple", "banana", "peach")
df <- data.frame(String = string, Word = word, stringsAsFactors = FALSE)

# 生成After列
df$After <- mapply(function(s, w) {
  sub(paste0("(.*\\b", w, "\\b).*"), "\\1", s)
}, df$String, df$Word)

# 查看结果
print(df)

关键逻辑说明

  • 正则表达式中的\\b是单词边界,确保匹配的是完整目标单词,避免出现类似把apple误匹配为apples的情况。
  • .*\\b[目标单词]\\b会匹配从字符串开头到目标单词的所有内容,str_extract或sub会提取这部分内容作为最终结果。

内容的提问来源于stack exchange,提问作者Polina Ermolaeva

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 19:23:06