How to highlight a substring based on a regex and turn it into Excel or HTML

女生的网名这么多〃 提交于 2019-12-23 03:12:39

问题


I have the following data frame:

dat <-  structure(list(value = c("YMNSMQEML", "FIYRHMFCV", "VLFKFDMFI", 
"KLLDRFPVA", "RVLDDFTKL")), .Names = "value", row.names = c(NA, 
-5L), class = c("tbl_df", "tbl", "data.frame"))

dat
#>       value
#> 1 YMNSMQEML
#> 2 FIYRHMFCV
#> 3 VLFKFDMFI
#> 4 KLLDRFPVA
#> 5 RVLDDFTKL

Given the following regex pattern L.{2}[FR] I would like to create an Excel where the substring is highlighted bold.

How can I achieve that?


UPDATE Using LIKE operator:

Option Explicit
Sub boldSubString_LIKE_OPERATOR()
    Dim R As Range, C As Range
    Dim MC As Object
    Set R = Range(Cells(2, 1), Cells(Rows.Count, 1).End(xlUp))

    For Each C In R
        C.Font.Bold = False
        If C.Text Like "L**F" Then
            Set MC = .Execute(C.Text)
            C.Characters(MC(0).firstindex + 1, MC(0).Length).Font.Bold = True
        End If
    Next C

End Sub

It breaks at Set MC = .Execute(C.Text), gives Compile Error Invalid or Unqualified Reference.


回答1:


To do this in Excel, you access the Characters property of the Range object: (and the contents needs to be an actual string; not a formula that returns a string)

Option Explicit
Sub boldSubString()
    Dim R As Range, C As Range
    Dim RE As Object, MC As Object
    Const sPat As String = "L.{2}[FR]"

'Range to be processed
Set R = Range(Cells(2, 1), Cells(Rows.Count, 1).End(xlUp))

'Initialize Regex engine
'Could use early binding if desireable
Set RE = CreateObject("vbscript.regexp")
With RE
    .Global = False
    .ignorecase = True
    .Pattern = sPat

    For Each C In R
        C.Font.Bold = False
        If .test(C.Text) Then
            Set MC = .Execute(C.Text)
            C.Characters(MC(0).firstindex + 1, MC(0).Length).Font.Bold = True
        End If
    Next C
End With

End Sub




回答2:


Since you mentioned HTML as well, you may generate an Rmarkdown HTML document and surround the pattern by the <b></b> tags. A minimal example using str_replace function from the stringr package:

---
output:
  html_document: default
title: "Pattern"
---


```{r echo = FALSE}
library(stringr)

## your data
dat <-  structure(list(value = c("YMNSMQEML", "FIYRHMFCV", "VLFKFDMFI",
"KLLDRFPVA", "RVLDDFTKL")), .Names = "value", row.names = c(NA,
-5L), class = c("tbl_df", "tbl", "data.frame"))


pattern <- "(L.{2}[FR])" # in brackets to reuse it in str_replace as \1
## surround \1 group with the bold tag
dat$value <-  str_replace(dat$value, pattern, "<b>\\1</b>")

knitr::kable(dat)
```



来源:https://stackoverflow.com/questions/51130741/how-to-highlight-a-substring-based-on-a-regex-and-turn-it-into-excel-or-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!