简体   繁体   中英

MS Word VBA macro to search and replace (Regex)

Suppose a word file contains

ab{cdefg{hij{k

And I want { to be moved one place to the right like

abc{defgh{ijk{

I need to make an array with all characters then run a loop with Regex search and replace

search:

({)(array[index])

replace:

$2$1

Plain Regex without loop won't work because I'm dealing with Indic text which have complex characters. I've done this on JavaScript and ExtendScript in inDesign, but I've no clue about VB. Can anyone please help?

This can be done using a Word wildcard search-and-replace:

With ActiveDocument.Range.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .ClearAllFuzzyOptions
    .Text = "(\{)(?)"           ' find opening brace followed by a single character
    .Replacement.Text = "\2\1"  ' swap positions
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchByte = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchFuzzy = False
    .MatchWildcards = True
End With
ActiveDocument.Range.Find.Execute Replace:=wdReplaceAll

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM