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

如何在DataFrame的HTML列中匹配[整数]模式并替换为ID列值

解决方案

给定的R语言示例数据如下:

ID <- c(15, 25, 90, 1, 23, 543)

HTML <- c("[demography_form][1]<div></table<text-align>[demography_form_date][1]", 
          "<text-ali>[geography_form][1]<div></table<text-align>[geography_form_date][1]", 
          "[social_isolation][1]<div></table<div><text-align>[social_isolation_date][1]", 
          "<text-align>[geography_form][1]<div></table<text-align>[geography_form_date][1]", 
          "<div>[demography_form][1]<div></table<text-align>[demography_form_date][1]", 
          "[geography_form][1]<div></table<text-align>[geography_form_date][1]</table")

df <- data.frame(ID, HTML)

需求是把每行HTML列中所有[数字]格式的内容,替换成对应行ID列的数值。下面提供两种实现方式:

方式一:使用tidyverse工具包(推荐)

先加载stringr(字符串处理)和purrr(逐行映射)两个包,然后逐行处理:

library(stringr)
library(purrr)

# 生成处理后的新列
df$HTML_processed <- map2_chr(df$HTML, df$ID, function(html_str, current_id) {
  # 匹配所有[数字]格式,替换为[当前行ID]
  str_replace_all(html_str, "\\[\\d+\\]", paste0("[", current_id, "]"))
})

方式二:使用基础R函数

如果不想额外加载包,用mapply结合gsub也能实现:

# 生成处理后的新列
df$HTML_processed <- mapply(function(html_str, current_id) {
  gsub("\\[\\d+\\]", paste0("[", current_id, "]"), html_str)
}, df$HTML, df$ID)

关键说明

  • 正则表达式\\[\\d+\\]:用来匹配所有被方括号包裹的整数,其中\\[和\\]是转义后的方括号(避免被正则解析为特殊语法),\\d+匹配1个或多个连续数字
  • 逐行映射:不管用map2_chr还是mapply,都是把每行的HTML字符串和对应的ID值配对处理,确保替换的是当前行的ID

处理后查看结果,比如第一行的HTML_processed会变成:
[demography_form][15]<div></table<text-align>[demography_form_date][15]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 20:13:24