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

R语言:匹配正则模式替换tibble中字符串的问题

解决字符串替换问题

你的问题出在替换字符串里直接使用了正则模式,而没有引用匹配到的实际内容。要实现需求,需要用捕获分组来保留中间的字母数字部分,再替换前后的.为_。

正确代码

library(tidyverse)

string <- tibble(METRIC = c('Eagle.PCT.Dominant', 'Eagle.PCT2.Dominant'))

string %>%
  mutate(newMETRIC = str_replace_all(METRIC, '\\.([A-Za-z0-9]+)\\.', '_\\1_'))

代码说明

  • 正则模式\\.([A-Za-z0-9]+)\\.:用括号()把中间的字母数字序列括起来,作为第1个捕获分组
  • 替换字符串_\\1_:\\1代表引用第1个捕获分组匹配到的内容,这样就会把.PCT.替换成_PCT_,.PCT2.替换成_PCT2_

运行结果

处理后的tibble会得到:

METRICnewMETRIC
Eagle.PCT.DominantEagle_PCT_Dominant
Eagle.PCT2.DominantEagle_PCT2_Dominant

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 12:32:42