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

如何使用Regex在Rmarkdown生成的HTML中按正则规则高亮文本

R Markdown实现分词正则匹配彩色高亮的方法

你可以按以下步骤直接实现需求,完整可运行的Rmd代码如下:

---
title: "分词高亮演示"
output: html_document
---

首先定义高亮样式,这部分代码运行时不会显示在最终HTML里:

{css, echo=FALSE}
.highlight-green {
  background-color: #d4edda;
  color: #155724;
  padding: 2px 4px;
  border-radius: 3px;
}
.highlight-blue {
  background-color: #cce5ff;
  color: #004085;
  padding: 2px 4px;
  border-radius: 3px;
}
.highlight-yellow {
  background-color: #fff3cd;
  color: #856404;
  padding: 2px 4px;
  border-radius: 3px;
}

然后编写数据处理和渲染逻辑:

# 加载HTML输出依赖包
library(htmltools)

# 输入你提供的原始数据
text <- c("When", " ", "Claire", " ", "visited", " ", "the", " ", "Statue", " ", "of", " ", "Liberty", " ", "for", " ", "the", " ", "first", " ", "time", ",", " ", "she", " ", "instantly", " ", "admired", " ", "it", " ", "as", " ", "a", " ", "symbol", " ", "of", " ", "freedom", ".") 
green <- c("^I$", "^you$", "^he$", "^she$", "^it$", "^we$", "^they$")
blue <- c("^the$", "^a$", "^an$")
yellow <- c("ed$")

# 分词匹配处理函数
process_token <- function(token) {
  # 空格直接返回不处理
  if (trimws(token) == "") return(token)
  # 匹配优先级:绿色>蓝色>黄色,你可以自行调整判断顺序修改优先级
  if (any(sapply(green, function(p) grepl(p, token)))) {
    return(sprintf('<span class="highlight-green">%s</span>', token))
  } else if (any(sapply(blue, function(p) grepl(p, token)))) {
    return(sprintf('<span class="highlight-blue">%s</span>', token))
  } else if (any(sapply(yellow, function(p) grepl(p, token)))) {
    return(sprintf('<span class="highlight-yellow">%s</span>', token))
  } else {
    return(token)
  }
}

# 批量处理所有分词并拼接为完整文本
processed_text <- paste(sapply(text, process_token), collapse = "")

# 输出为可识别的HTML内容,不会转义标签
HTML(processed_text)

将上述所有内容按顺序写入后缀为.Rmd的文件,点击RStudio的「编织」按钮,即可生成对应高亮效果的HTML文件。你可以根据需求修改CSS中的颜色、边距等样式参数,也可以新增正则组和对应的高亮样式类。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 22:15:03