MS-Word VBA, Regex, replace format only of first capturing group

别说谁变了你拦得住时间么 提交于 2020-01-05 08:07:17

问题


I try to record a replacement in VBA using Search & Replace with wildcards:

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.

giving: "1 normal" with the 1 in blue and "normal" in the original format..

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"

Any pointers, maybe straight away using VBA?


回答1:


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



回答2:


Use this regex instead: ^ {3}(normal.*)

^          # Matched the start of the string
 {3}       # Followed by 3 spaces
(normal.*) # Followed by normal + anything else (captured)

Tested with 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


来源:https://stackoverflow.com/questions/13489345/ms-word-vba-regex-replace-format-only-of-first-capturing-group

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!