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

请求编写正则表达式替换英文月缩写+数字日的日期格式

解决方案

可以使用R语言的stringr包配合正则表达式完成替换操作,具体步骤如下:

1. 匹配规则说明

需要匹配的格式是英文三字母月份缩写(小写)+1-2位数字,对应的正则表达式为:
\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d{1,2}\b

各部分含义:

  • \b:单词边界,确保匹配独立的日期片段,避免误匹配包含类似字符的其他单词
  • (jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec):覆盖所有英文三字母月份缩写
  • \d{1,2}:匹配1到2位数字

2. 完整代码实现

# 加载所需工具包
library(dplyr)
library(stringr)

# 定义原始数据框
df_new <- data.frame(
  given_info=c('oct12 is given','he received on jan1',
               'lets go on dec12','also feb04 is right')
)

# 执行替换操作
df_result <- df_new %>%
  mutate(given_info = str_replace_all(given_info, 
                                      "\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\d{1,2}\\b", 
                                      "specific time"))

# 查看最终结果
df_result %>% select(given_info)

3. 输出结果

运行代码后得到的结果与期望一致:

given_info
1      specific timeis given
2 he received on specific time
3    lets go on specific time
4 also specific timeis right

如果需要支持大小写混合的月份缩写(比如Oct12),可以在正则中添加不区分大小写标识,将正则表达式修改为:
(?i)\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\d{1,2}\b
对应替换代码中的正则部分改为:
"(?i)\\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\\d{1,2}\\b"

内容的提问来源于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 00:25:22