使用正则表达式突出显示 HTML 中使用 Rmarkdown 生成的文本

Use Regex to highlight a text in HTML generated with Rmarkdown

我有一个包含标记化文本的向量和一些其他正则表达式向量,如下所示:

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$")

我如何使用 Rmarkdown 编织一个 HTML 文本作为人类可读的文本打印,并用不同颜色突出显示正则表达式?像这样:

谢谢。

实现您想要的结果的一个选项可能如下所示:

---
output: html_document
---

```{r echo=FALSE}
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$")
```

```{r}
regex <- lapply(list(lightgreen = green, cyan = blue, yellow = yellow), function(x) {
  x <- paste(x, collapse = "|")
  paste0("(", x, ")")
})
for (i in seq_along(regex)) {
  text <- gsub(regex[[i]], paste0("<span style='background-color:", names(regex)[i], "'>\1</span>"), text)  
}
```

`r paste(text, collapse = "")`