[英]MS-Word VBA, Regex, replace format only of first capturing group
I try to record a replacement in VBA using Search & Replace with wildcards: 我尝试使用通配符搜索和替换在VBA中记录替换:
I have strings comprised of 3 white spaces followed by the word normal, like " normal", and want to replace the 3 leading spaces with "1 " (a 1 followed by two spaces) the "1" in a blue font. 我有3个空格组成的字符串,后跟“正常”一词,例如“ normal”,并希望将3个前导空格替换为蓝色字体中的“ 1”(先加上两个空格再加上1)。
giving: "1 normal" with the 1 in blue and "normal" in the original format.. 给出:“ 1正常”,蓝色为1,原始格式为“正常”。
I tried to match: 我尝试匹配:
([^s]{3})normal
but when replacing with a new format I always get the whole string re-formatted.. how to preserve the original format for the string "normal" 但是当替换为新格式时,我总会重新格式化整个字符串。.如何为字符串“ normal”保留原始格式
Any pointers, maybe straight away using VBA? 任何指针,也许直接使用VBA?
I managed to do what I want. 我设法做自己想做的事。 However, I don't use Regex and I guess there is a more elegant way to do it (I do two replacements to get where I want).
但是,我不使用Regex,我想还有一种更优雅的方法(我做了两次替换以达到所需的位置)。 I think the key word is "lookaround" but I didn't get around applying it.
我认为关键字是“环视”,但我并没有绕过它。
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
Use this regex
instead: ^ {3}(normal.*)
请改用此
regex
: ^ {3}(normal.*)
^ # Matched the start of the string
{3} # Followed by 3 spaces
(normal.*) # Followed by normal + anything else (captured)
Tested with sed
: 经过
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.