我有以下数据框:
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,其中的子字符串以粗体突出显示。
我怎样才能做到这一点呢?
使用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)
处中断,给出编译错误无效或未限定的引用。
发布于 2018-07-02 18:53:11
要在Excel中执行此操作,请访问Range
对象的Characters
属性:(并且内容必须是实际的字符串,而不是返回字符串的公式)
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
发布于 2018-07-02 16:09:43
既然您也提到了HTML,那么您可以生成一个Rmarkdown HTML文档,并用<b></b>
标记将模式包围起来。使用stringr
包中的str_replace
函数的最小示例:
---
output:
html_document: default
title: "Pattern"
---
```{r echo = FALSE}
库(字符串)
您的数据
dat <- structure(列表(value= c("YMNSMQEML","FIYRHMFCV","VLFKFDMFI",
"KLLDRFPVA",“RVLDDFTKL”),.Names = "value",row.names = c(NA,
-5L),类= c("tbl_df","tbl","data.frame"))
括号中的pattern <- "(L.{2}FR)“#,以便在str_replace中将其重用为\1
用粗体标记将\1组括起来
dat$value <- str_replace(dat$value,模式,"\1")
kable::kable(Dat)
https://stackoverflow.com/questions/51130741
复制相似问题