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

如何在R语言中为字母数字字符串的数字部分补前导零至4位?

实现方法

方法一:基础R正则替换+sprintf

利用正则捕获组分离前缀和数字部分,再通过sprintf补前导零后拼接:

v <- c("AB_124", "BAE_1", "LOED_1234", "H_01")
# 生成带占位符的模板,再填充补零后的数字
sprintf(sub("^(.*_)(\\d+)$", "\\1%04d", v), as.integer(sub(".*_(\\d+)$", "\\1", v)))

运行结果:

[1] "AB_0124"   "BAE_0001"  "LOED_1234" "H_0001"

方法二:基础R正则匹配替换

通过regmatches提取数字部分,修改后替换回原向量:

v <- c("AB_124", "BAE_1", "LOED_1234", "H_01")
# 提取末尾的数字片段
num_matches <- regmatches(v, gregexpr("\\d+$", v))
# 将数字转为整数后补零,再替换回原位置
regmatches(v, gregexpr("\\d+$", v)) <- lapply(num_matches, function(x) sprintf("%04d", as.integer(x)))
v

运行结果同上。

方法三:stringr包简洁实现

借助stringr的字符串处理函数,用str_replace配合匿名函数对数字部分补零:

library(stringr)
v <- c("AB_124", "BAE_1", "LOED_1234", "H_01")
str_replace(v, "\\d+$", function(x) str_pad(x, width = 4, side = "left", pad = "0"))

运行结果同上。

方法四:拆分-处理-合并(stringr)

先按下划线拆分字符串,单独处理数字部分后再合并:

library(stringr)
v <- c("AB_124", "BAE_1", "LOED_1234", "H_01")
# 拆分为前缀和数字两部分
split_parts <- str_split_fixed(v, "_", n = 2)
# 数字部分补零后与前缀拼接
paste0(split_parts[, 1], "_", str_pad(split_parts[, 2], 4, side = "left", pad = "0"))

运行结果同上。

内容的提问来源于stack exchange,提问作者Maël

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 15:10:00