繁体   English   中英

MS-Word VBA,正则表达式,仅替换第一个捕获组的格式

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

我尝试使用通配符搜索和替换在VBA中记录替换:

我有3个空格组成的字符串,后跟“正常”一词,例如“ normal”,并希望将3个前导空格替换为蓝色字体中的“ 1”(先加上两个空格再加上1)。

给出:“ 1正常”,蓝色为1,原始格式为“正常”。

我尝试匹配:

([^s]{3})normal

但是当替换为新格式时,我总会重新格式化整个字符串。.如何为字符串“ normal”保留原始格式

任何指针,也许直接使用VBA?

我设法做自己想做的事。 但是,我不使用Regex,我想还有一种更优雅的方法(我做了两次替换以达到所需的位置)。 我认为关键字是“环视”,但我并没有绕过它。

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

请改用此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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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