我有以下的数据帧:
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,其中子被突出大胆。
我怎样才能做到这一点?
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)
,给人编译错误无效的或不合格的参考。
要做到这一点在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
既然你提到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)
```