如何基于正则表达式突出的子串,并把它变成Excel或HTML

问题描述 投票:1回答:2

我有以下的数据帧:

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

鉴于以下regex pattern L.{2}[FR]我想创建一个Excel,其中子被突出大胆。

enter image description here

我怎样才能做到这一点?


UPDATE使用LIKE操作:

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

它打破了在Set MC = .Execute(C.Text),给人编译错误无效的或不合格的参考。

html r excel ms-office
2个回答
1
投票

要做到这一点在Excel中,您可以访问Characters属性Range对象:(和内容必须是一个实际的字符串;不返回字符串的公式)

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

enter image description here


4
投票

既然你提到HTML以及,你可能会产生Rmarkdown HTML文档,并通过<b></b>标签包围的图案。使用str_replace函数从stringr包的最小例如:

---
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)
```

click here to see the result

© www.soinside.com 2019 - 2024. All rights reserved.