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

如何通过单次str_replace_all()调用实现字符串多模式替换?

如何单次调用str_replace_all()完成多模式文本替换

在进行文本替换时,我很少只需要替换一种模式,常常会连续调用多次str_replace_all()函数,如下示例代码显得十分重复。是否可以仅调用一次str_replace_all()完成这些替换?

library(dplyr)
library(stringr)

text <- r'(mother, father, grandmother, and grandfather)'

# 有没有更简洁的写法?
text %>% 
  str_replace_all(
    pattern = r'(\bmother\b)',
    replacement = 'mom'
  ) %>% 
  str_replace_all(
    pattern = r'(\bfather\b)',
    replacement = 'dad'
  ) %>% 
  str_replace_all(
    pattern = 'grandmother',
    replacement = 'grandma'
  ) %>% 
  str_replace_all(
    pattern = 'grandfather',
    replacement = 'grandpa'
  ) %>% 
  str_replace_all(
    pattern = r'(\band\b)',
    replacement = '&'
  )
#> [1] "mom, dad, grandma, & grandpa"

我设想可以借助查找表来实现:

df_lookup <-
  tribble(
    ~pattern,           ~replacement,
    r'(\bmother\b)',    'mom',
    r'(\bfather\b)',    'dad',
    'grandmother',      'grandma',
    'grandfather',      'grandpa',
    r'(\band\b)',       '&'
  )

解决方案

方法1:用命名向量直接传递规则

str_replace_all()原生支持接收命名向量作为参数——向量名称为匹配模式,向量值为对应替换文本,一次调用即可完成所有替换:

library(dplyr)
library(stringr)

text <- r'(mother, father, grandmother, and grandfather)'

# 定义替换规则的命名向量
replace_rules <- c(
  r'(\bmother\b)' = 'mom',
  r'(\bfather\b)' = 'dad',
  'grandmother' = 'grandma',
  'grandfather' = 'grandpa',
  r'(\band\b)' = '&'
)

# 单次调用完成替换
text %>% str_replace_all(replace_rules)
#> [1] "mom, dad, grandma, & grandpa"

方法2:基于查找表转换实现

如果已经有了预设的df_lookup查找表,只需将其转换为命名向量即可复用:

# 从查找表生成命名向量
replace_rules_from_df <- setNames(df_lookup$replacement, df_lookup$pattern)

# 执行替换
text %>% str_replace_all(replace_rules_from_df)
#> [1] "mom, dad, grandma, & grandpa"

注意:替换顺序遵循规则的排列顺序,若存在文本同时匹配多个模式,排在前面的规则会优先生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 09:43:18