我尝试使用通配符搜索和替换在 VBA 中记录替换:
我有由 3 个空格后跟单词 normal 组成的字符串,例如“normal”,并且想用蓝色字体的“1”(一个 1 后跟两个空格)替换 3 个前导空格。
给出:“1 normal”,1为蓝色,“normal”为原始格式..
我试图匹配:
([^s]{3})normal
但是当用新格式替换时,我总是会重新格式化整个字符串..如何保留字符串“正常”的原始格式
任何指针,也许直接使用VBA?
我设法做我想做的事。但是,我不使用正则表达式,我想有一种更优雅的方式来做到这一点(我做了两次替换来得到我想要的地方)。我认为关键词是“环顾四周”,但我没有绕过应用它。
Sub replace_3spaces()
Dim str_after As String
Dim re_number As Integer
str_after = "normal"
re_number = "1"
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
With Selection.Find
.Text = "([^s]{3})" & "(" & str_after & ")"
.Replacement.Text = "§§§\2"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
Selection.Find.ClearFormatting
Selection.Find.Replacement.Font.ColorIndex = wdBlue
With Selection.Find
.Text = "§§§"
.Replacement.Text = re_number & " "
.Forward = True
.Wrap = wdFindContinue
.Format = True
.MatchCase = False
.MatchWholeWord = False
.MatchAllWordForms = False
.MatchSoundsLike = False
.MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll
End Sub
改用这个regex
:^ {3}(normal.*)
^ # Matched the start of the string
{3} # Followed by 3 spaces
(normal.*) # Followed by normal + anything else (captured)
经测试sed
:
$ cat file.txt
normal string
no spaces
two spaces
another normal string
$ sed -E 's/^ {3}(normal.*)/1 \1/' file.txt
1 normal string
no spaces
two spaces
another normal string