如何用新字符串替换正则表达式

时间:2012-11-29 22:41:08

标签: regex vba ms-word

我想用新字符串替换所有三个字母的单词。 MsgBox显示变量threeLetterWord具有新值,但文本不会更改。

Sub ShowThreeLetterWords()

Set threeLetterRegExp = New RegExp
   threeLetterRegExp.Pattern = "\b[a-zA-Z]{3}\b"
   threeLetterRegExp.Global = True

   Dim threeLetterWords As MatchCollection
   Set threeLetterWords = threeLetterRegExp.Execute(ActiveDocument.Range)

   For Each threeLetterWord In threeLetterWords
      threeLetterWord = threeLetterRegExp.Replace(threeLetterWord, "sasa")
      MsgBox threeLetterWord
   Next threeLetterWord
 End Sub

1 个答案:

答案 0 :(得分:1)

正则表达式很好。我认为唯一的问题是你不应该在循环中再次分配treeLetterWord,因为它是“foreach迭代变量”。

直接

MsgBox threeLetterRegExp.Replace(threeLetterWord, "sasa")

应该没问题