【问题标题】:MS-Word VBA, Regex, replace format only of first capturing groupMS-Word VBA,正则表达式,仅替换第一个捕获组的格式
【发布时间】:2012-11-22 15:48:34
【问题描述】:

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

我的字符串由 3 个空格和单词 normal 组成,例如“normal”,并且想用“1”(一个 1 后跟两个空格)替换前面的 3 个空格,蓝色字体的“1” .

给:“1 normal”,蓝色的 1 和原始格式的“normal”..

我尝试匹配:

([^s]{3})normal

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

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

【问题讨论】:

  • 我假设您在 VBA 中执行此操作,因为正常查找不支持正则表达式 AFAIK。你应该说清楚并发布相应的代码,否则我认为这将作为“离题”关闭
  • @stema:我根据您的评论指定了我的问题。顺便说一句,MS_word 搜索和替换为通配符会进行类似正则表达式的匹配。
  • 接近投票还为时过早,任何可能审查此内容的人都应该忽略。

标签: regex vba ms-word


【解决方案1】:

我设法做我想做的事。但是,我不使用正则表达式,我想有一种更优雅的方式来做到这一点(我做了两次替换来得到我想要的地方)。我认为关键词是“环顾四周”,但我没有绕过应用它。

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】:

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

【讨论】:

  • 谢谢@sudo_o - 我应该首先避免使用 Word 通配符并使用正确的正则表达式(^s 是 Word 标准搜索和替换中空格的通配符..)。对于您的正则表达式:我真的想匹配字符串“正常”(前面有三个空格),而不是所有空格在行首重复 3 次..
猜你喜欢
  • 2020-11-14
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
  • 2014-06-19
  • 2010-11-19
  • 2023-01-22
相关资源
最近更新 更多