2012-11-21 71 views
1

我試圖記錄使用搜索&在VBA的替代品,使用通配符替換格式:MS-Word中VBA,正則表達式,只更換的第一個捕獲組

我有由3個空格後面的字普通字符串,像「正常」,並希望用「1」(1後面跟兩個空格)替換3個前導空格中的藍色字體「1」。

,並提供:「1正常」,在藍色原始格式爲「正常」的1 ..

我試圖匹配:

([^s]{3})normal 

但隨着一種新的格式,我總是更換時得到整個字符串重新格式化.. 如何保留字符串「正常」的原始格式

任何指針,可能直接使用VBA?

+0

我假設你在VBA中這樣做,因爲正常查找不支持正則表達式AFAIK。你應該清楚這一點,併發布相應的代碼,否則我認爲這將被關閉爲「脫離主題」 – stema

+1

@stema:我根據你的評論指定了我的問題。順便說一句,MS_word搜索和替換通配符不會像正則表達式匹配。 – Kay

+0

關閉選票還爲時過早,任何其他可能會對此進行審查的人都應該忽略。 – brettdj

回答

0

我設法做我想做的。然而,我不使用正則表達式,我想有一個更優雅的方式來做到這一點(我做了兩個替換,以獲得我想要的)。我認爲關鍵詞是「lookaround」,但我沒有得到解決。

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

I重新發布了關於這兩個程序優化的問題[http://stackoverflow.com/questions/13562820/optimizing-find-and-replace-ms-word-vba-script](http://stackoverflow.com/ questions/13562820/optimize-find-and-replace-ms-word-vba-script「LINK」) – Kay

0

使用此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 
+0

謝謝@sudo_o - 我應該避免使用Word通配符,並首先使用正確的正則表達式(^ s是Word標準搜索和替換..中空格的通配符)。對你的正則表達式:我真的想匹配字符串「正常」(前面有三個空格),並非所有空格在一行的開始處重複3次.. – Kay

+0

@Kay回答已更新以反映此.. –