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

编写正则表达式替换数据框文本列中独立的ris为LTD

独立单词"ris"(大小写不敏感)替换为"LTD"的实现方案

需求说明

需要将数据框name列中作为独立单词存在的ris(含RIS、Ris等所有大小写形式)替换为LTD,独立单词指该词汇前后无其他字符(即被单词边界包裹)。

实现代码

以下两种方案均可实现需求,按需选择:

方案1:基础R原生实现

# 原始数据集
df <- data.frame(
  name=c('Chris is nice','ris is nice and ris is old','Risoto is bad','RIS is bad',
         'rising is nice ', 'Prosis is ris and big','Ris is tall','doris is short')
)

# 执行替换:\\b匹配单词边界,ignore.case=TRUE忽略大小写
df$name <- gsub(pattern = "\\bris\\b", replacement = "LTD", x = df$name, ignore.case = TRUE)

# 查看结果
df$name

方案2:tidyverse风格实现

如果习惯使用tidyverse工具链,可用stringr包完成替换:

library(tidyverse)

# 原始数据集
df <- tibble(
  name=c('Chris is nice','ris is nice and ris is old','Risoto is bad','RIS is bad',
         'rising is nice ', 'Prosis is ris and big','Ris is tall','doris is short')
)

# 执行替换,regex()指定正则并忽略大小写
df <- df %>% 
  mutate(name = str_replace_all(name, regex("\\bris\\b", ignore_case = TRUE), "LTD"))

# 查看结果
df$name

替换结果

执行后得到的name列内容如下:

[1] "Chris is nice"          "LTD is nice and LTD is old" "Risoto is bad"          
[4] "LTD is bad"             "rising is nice "         "Prosis is LTD and big"  
[7] "LTD is tall"            "doris is short"

关键细节说明

  • \\b是正则表达式的单词边界,确保只匹配独立的ris单词,不会误替换Chris、Risoto、rising、doris这类包含ris字符但非独立单词的内容。
  • ignore.case=TRUE(或regex(..., ignore_case=TRUE))参数确保匹配所有大小写变体(RIS、Ris、ris等)。

内容的提问来源于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 12:15:26