使用正则expression式提取URL

我收到来自同一网站的10或12封电子邮件,我想使用正则expression式(如果可能)提取特定的URL,并将其粘贴到正确的Excel文件中。 电子邮件是在Outlook中,我已经有一个VBA脚本(从Outlook VBA运行),我用来提取主题和发件人。 但是,我真的需要在每封电子邮件中的特定URL作为第三条提取的信息。

我试图创build一系列步骤来:

  1. 创buildRegEx
  2. 将RegEx应用于当前电子邮件
  3. 将提取的URL放入Excel文档中。

但是,无论我创造了什么,都是悲惨的。 下面粘贴的VBA总是有效,直到我在附加的RegEx部分中写入。

我相信我有正确的模式:

/http:\/\/www.changedetection.com\/log(.*)/ig 

每当我运行新的VBA脚本,它什么也不做。 旧的代码一直工作。 代码被写入到这个Outlook会话(只是为了澄清),因为mailitem需要从脚本运行。

 Const xlUp As Long = -4162 Sub ExportToExcel(MyMail As MailItem) Dim strID As String, olNS As Outlook.NameSpace Dim olMail As Outlook.MailItem Dim strFileName As String Dim strBody As String Dim Reg1 As RegExp Dim M1 As MatchCollection Dim M As Match Set Reg1 = New RegExp With Reg1 .Pattern = "http://www\.changedetection\.com/log(.*)" .IgnoreCase = True .Global = True End With If Reg1.test(olMail.Body) Then Set M1 = Reg1.Execute(olMail.Body) For Each M In M1 strBody = M.SubMatches(1) Next End If '~~> Excel Variables Dim oXLApp As Object, oXLwb As Object, oXLws As Object Dim lRow As Long strID = MyMail.EntryID Set olNS = Application.GetNamespace("MAPI") Set olMail = olNS.GetItemFromID(strID) '~~> Establish an EXCEL application object On Error Resume Next Set oXLApp = GetObject(, "Excel.Application") '~~> If not found then create new instance If Err.Number <> 0 Then Set oXLApp = CreateObject("Excel.Application") End If Err.Clear On Error GoTo 0 '~~> Show Excel oXLApp.Visible = True '~~> Open the relevant file Set oXLwb = oXLApp.Workbooks.Open("M:\Monitor\Monitor_Test_1.xlsx") '~~> Set the relevant output sheet. Change as applicable Set oXLws = oXLwb.Sheets("Test") lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1 '~~> Write to outlook With oXLws ' '~~> Code here to output data from email to Excel File '~~> For example ' .Range("A" & lRow).Value = olMail.Subject .Range("B" & lRow).Value = olMail.SenderName .Range("C" & lRow).Value = strBody ' End With '~~> Close and Clean up Excel oXLwb.Close (True) oXLApp.Quit Set Reg1 = Nothing Set oXLws = Nothing Set oXLwb = Nothing Set oXLApp = Nothing Set olMail = Nothing Set olNS = Nothing End Sub 

VBScript正则expression式模式不使用/来指示开始和结束。 在结尾之后,他们也不会使用ig来表示不区分大小写或全局。 而是使用IgnoreCaseGlobal属性。

例如:

 With Reg1 .Pattern = "http://www\.changedetection\.com/log(.*)" .IgnoreCase = True .Global = True End With 

如果您正在查找有关RegExp对象的更多信息, 这里有一个很好的参考 。