VBA正则表达式-选择所有斜体文本-包含空格

时间:2018-12-30 08:20:11

标签: regex vba ms-word

因此,我有以下VB脚本,该脚本用<em>标签包裹每个斜体字。效果很好,我只想扩展RE来查找所有斜体文本以及空格,因此它用<em>标签而不是每个单词都包裹了整个部分。

我尝试添加" "(\S)等,但是它仍然没有选择带有空格的整个字符串,而是每个单词都单独选择。

Selection.Find.ClearFormatting
Selection.Find.Font.Italic = True
Selection.Find.Replacement.ClearFormatting
Selection.Find.Replacement.Font.Italic = False
With Selection.Find
    .Text = "([a-zA-Z0-9\:]{1,})"
    .Replacement.Text = "<em>\1</em>"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchKashida = False
    .MatchDiacritics = False
    .MatchAlefHamza = False
    .MatchControl = False
    .MatchAllWordForms = False
    .MatchSoundsLike = False
    .MatchWildcards = True
End With
Selection.Find.Execute Replace:=wdReplaceAll

示例文本:

  

askdjaksdj kaljdkjsadska askdjlkdjl aksdjlskjd sakdj sakjdlkjsd askdj   alkjd lksadj lsajd lksajd lksaj dlkaj dlksajd lkjs dkl jaks dj   askdljsakdjska djskla djlksa djsadj

运行原始宏后:

askdjaksdj kaljdkjsadska <em>askdjlkdjl</em> <em>aksdjlskjd</em> <em>sakdj</em> <em>sakjdlkjsd</em> <em>askdj</em> <em>alkjd</em> <em>lksadj</em> <em>lsajd</em> <em>lksajd</em> <em>lksaj</em> <em>dlkaj</em> <em>dlksajd</em> <em>lkjs</em> <em>dkl</em> <em>jaks</em> <em>dj</em> askdljsakdjska djskla djlksa djsadj

2 个答案:

答案 0 :(得分:1)

尝试一下:

.Text = "([a-zA-Z0-9\: ]{1,})"

代替

.Text = "([a-zA-Z0-9\:]{1,})

在运行宏之前:

enter image description here

运行宏后:

enter image description here

宏:

enter image description here

答案 1 :(得分:0)

您不需要通配符或RegEx。试试:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Content.Find
  .ClearFormatting
  .Replacement.ClearFormatting
  .Text = ""
  .Replacement.Text = "<em>^&</em>"
  .Font.Italic = True
  .Replacement.Font.Italic = False
  .Forward = True
  .Format = True
  .Wrap = wdFindContinue
  .MatchWildcards = False
  .Execute Replace:=wdReplaceAll
End With
Application.ScreenUpdating = True
End Sub

也请注意,无需选择任何内容。