【发布时间】:2017-12-02 08:09:25
【问题描述】:
我可以使用正则表达式在 Microsoft Word 文档中查找和替换 IP 地址,但是我无法对电子邮件地址和 URL 执行相同的操作。
以下是经过测试的 URL 和电子邮件地址的正则表达式,因此我知道它们有效。我一直无法让宏使用它们进行查找和替换。
网址:“((https|http)://)?([0-9a-zA-z.-]+).([0-9a-zA-Z.]{2,6})( [0-9a-zA-z.-/]+)"
电子邮件:“[a-zA-Z0-9.]+(\@)[a-zA-Z]+(.)[a-zA-Z0-9]{2,6}”
Sub Test()
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
Selection.Find.Replacement.ClearFormatting
Selection.Find.MatchWildcards = True
' Remove IPs
With Selection.Find
.Text = "[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"
.Replacement.Font.ColorIndex = wdRed
.Replacement.Text = "[IP REMOVED]"
.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
我使用以下代码测试了我的正则表达式:
Sub Test_Regex()
Dim objRegExp As Object
Set objRegExp = CreateObject("vbscript.regexp")
objRegExp.Global = IsGlobal1
objRegExp.Pattern = "((https|http)\:\/\/)?([0-9a-zA-z\.\-]+)\.([0-9a-zA-Z\.]{2,6})([0-9a-zA-z\.\-\/]+)?"
objRegExp.IgnoreCase = Not IsCaseSensitive1
RegExpReplace = objRegExp.Replace("google.com/asdasd/asda/asda.cssd", "RegexWorks")
MsgBox (RegExpReplace)
End Sub
@Wiktor Stribiżew -- 我尝试根据您最近的评论使用正则表达式以保留格式,但当我运行它时它仍在剥离格式。这个 urlPattern 正则表达式和你描述的一样吗?
Sub Test()
Dim urlPattern As String: urlPattern = "((https)\:\/\/)([0-9a-zA-z\.\-]+)\.([0-9a-zA-Z\.]{2,6})([0-9a-zA-z\.\-\/]+)"
Dim regExp As Object
Set regExp = CreateObject("vbscript.regexp")
With regExp
.Pattern = urlPattern
.Global = True
ActiveDocument.Range = regExp.Replace(ActiveDocument.Range, "[REDACTED]")
End With
End Sub
【问题讨论】:
-
它使用什么样的正则表达式引擎?
-
我不认为你需要这些逃逸。尝试使用 C 风格的字符串
"((https|http)://)?([0-9a-zA-z.-]+)\\.([0-9a-zA-Z.]{2,6})([0-9a-zA-Z./-]+)?"我在课堂上将A-z更正为A-Z。 -
您很困惑,因为
Selection.Find使用 wildcard 表达式,并且在 VBA 代码中,您使用了 Microsoft VBScript Regular Expressions 5.5 regular 表达式。通配符表达式没有 零个或多个 / 零个或一个 量词。它们不能匹配空字符串。 -
如果我明白你在问什么,那就是 VBA
-
@sln -- 使用 C-Style 字符串,..它给了我以下错误-并指向 Selection.find.execute 行:运行时错误'5560':查找内容text 包含无效的模式匹配表达式。