1
votes

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?

2
I assume you are doing this in VBA, because the normal find does not support regex AFAIK. You should make this clear and post the according code, otherwise I assume this will be closed as "off topic"stema
@stema: I specified my questions according to your comment.. BTW, MS_word Search & Replace with wildcards does regex-like matching.Kay
The close votes are premature and should be ignored by anyone else who may review this.brettdj

2 Answers

1
votes

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
0
votes

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