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

R语言中用str_replace_all/gsub正则替换数字后小写字母为大写

解决街道地址中数字后单个小写字母转大写的问题

需求说明

给定包含街道地址的列:

df_col <- c("100 W 10th St", "200 Drury Ln 2a", "300 W 10th St", "400b Drury Ln")

需要将所有数字后紧跟的单个小写字母转为大写,最终结果:

df_col <- c("100 W 10th St", "200 Drury Ln 2A", "300 W 10th St", "400B Drury Ln")

stringr::str_replace_all 解决方案

你之前的错误在于替换参数直接写了正则表达式,而str_replace_all需要用捕获组提取目标内容,再对捕获的字母做大小写转换。

代码实现

library(stringr)
library(dplyr)

df <- tibble(df_col = c("100 W 10th St", "200 Drury Ln 2a", "300 W 10th St", "400b Drury Ln"))

df <- df %>%
  mutate(df_col = str_replace_all(df_col, "\\b(\\d+)([a-z])\\b", function(x) {
    matches <- str_match(x, "\\b(\\d+)([a-z])\\b")
    paste0(matches[2], str_to_upper(matches[3]))
  }))

正则与逻辑解释

  • \\b(\\d+)([a-z])\\b:用括号创建两个捕获组
    • (\\d+):捕获一个或多个数字(第一组)
    • ([a-z]):捕获紧跟数字后的单个小写字母(第二组)
    • \\b:确保匹配的是独立的"数字+字母"单词(避免误匹配"10th"这类包含数字但字母不紧跟的情况)
  • 替换函数中,通过str_match提取两组内容,保留数字部分,将字母部分用str_to_upper转为大写后拼接。

更简洁的写法(反向引用)

利用str_replace_all的公式语法,结合反向引用可以简化代码:

df <- df %>%
  mutate(df_col = str_replace_all(df_col, "\\b(\\d+)([a-z])\\b", 
                                  ~ paste0(.x[2], str_to_upper(.x[3]))))

备选方案:base R 的 gsub(Perl 模式)

如果想用base R工具,可开启Perl模式,利用\\U标记直接将匹配的字母转为大写:

df$df_col <- gsub("\\b(\\d+)([a-z])\\b", "\\1\\U\\2", df$df_col, perl = TRUE)
  • \\1:引用第一个捕获组的数字内容
  • \\U\\2:将第二个捕获组的小写字母转为大写(仅在Perl模式下生效)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:54:59