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

在R语言中替换文本列中指定格式的数字为自定义字符

R语言替换指定格式数字序列为固定文本

可以通过stringr包的正则替换功能实现需求,核心是编写匹配目标格式的正则表达式,结合dplyr完成数据框列的处理:

步骤1:加载依赖包

library(dplyr)
library(stringr)

步骤2:定义示例数据并处理

df <- data.frame(
  notes = c(
    'my number is 123-41-567',
    "321 12 788 is valid",
    'why not taking 987-012-678',
    '120 967 325 is correct'
  )
)

# 执行替换操作
df_processed <- df %>%
  mutate(notes = str_replace_all(notes, 
                                "\\b(?:\\d{2,3}[- ]){2}\\d{2,3}\\b", 
                                "aaaaa"))

步骤3:查看处理结果

df_processed %>% select(notes)

输出结果与预期一致:

notes
1     my number is aaaaa
2        aaaaa is valid
3   why not taking aaaaa
4     aaaaa is correct

正则表达式说明

\\b(?:\\d{2,3}[- ]){2}\\d{2,3}\\b 各部分含义:

  • \\b:单词边界,确保匹配完整的数字序列,避免误匹配数字片段
  • (?:\\d{2,3}[- ]){2}:非捕获组,重复2次匹配「2-3位数字 + 连字符/空格」的组合
  • \\d{2,3}:匹配最后一组2-3位数字
    该正则可精准匹配你需要替换的「连字符/空格分隔、总位数8-9位」的数字序列。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 17:01:25