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

如何从R语言数据框的文本列中移除任意格式的日期?

移除文本列中任意格式的日期(R语言实现)

你的数据集里的日期主要是4位年份+分隔符(空格/横杠/斜杠)+2位月份+分隔符+2位日期的格式,用正则表达式就能精准匹配并移除。以下是两种实现方式:

方法一:结合tidyverse工具(推荐)

加载dplyr和stringr包,用str_remove_all批量处理文本列:

library(dplyr)
library(stringr)

# 原始数据
df <- data.frame(
  text=c('tommorow is 2022 11 03',"I married on 2020-01-01",
         'why not going there on 2023/01/14','2023 08 01 will be great')
)

# 移除所有目标格式的日期
df_cleaned <- df %>%
  mutate(text = str_remove_all(text, "\\b\\d{4}[-/\\s]\\d{2}[-/\\s]\\d{2}\\b"))

# 查看处理后的结果
df_cleaned %>% select(text)

运行后输出结果:

text
1            tommorow is 
2            I married on 
3 why not going there on 
4            will be great

方法二:基础R实现

如果不想加载额外包,用gsub也能完成:

df <- data.frame(
  text=c('tommorow is 2022 11 03',"I married on 2020-01-01",
         'why not going there on 2023/01/14','2023 08 01 will be great')
)

df$text <- gsub("\\b\\d{4}[-/\\s]\\d{2}[-/\\s]\\d{2}\\b", "", df$text)

# 查看结果
df %>% select(text)

正则表达式说明

\\b\\d{4}[-/\\s]\\d{2}[-/\\s]\\d{2}\\b 各部分含义:

  • \\b:匹配单词边界,避免误删包含类似数字的其他词汇
  • \\d{4}:匹配4位数字(对应年份)
  • [-/\\s]:匹配横杠、斜杠或空格三种分隔符
  • \\d{2}:匹配2位数字(对应月份和日期)

如果后续遇到其他日期格式(比如日/月/年),可以调整正则表达式的结构来适配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:40:27