【问题标题】:Excel VBA Regular Expressions Working with Quotes使用引号的 Excel VBA 正则表达式
【发布时间】:2013-12-17 11:31:06
【问题描述】:

我需要声明一个字符串以用作正则表达式模式。

字符串是: (?

通常要在 VBA 中声明一个用于 Reg Exp 的字符串,请用双引号括起来,因此它看起来像这样: "(?

这个: "(?

这个 "(?

有效,但是当我使用 Msgbox 查看模式时,它看起来像这样:

(?

因此在 RegEx 中无法正常工作。

啊!

这是我用于测试的代码:

    Sub tester()
        Dim PATH_TO_FILINGS As String
        'PATH_TO_FILINGS = "www.sec.gov/Archives/edgar/data/1084869/000110465913082760"
        PATH_TO_FILINGS = "www.sec.gov/Archives/edgar/data/1446896/000144689612000023"
        MsgBox GetInstanceDocumentPath(PATH_TO_FILINGS)
    End Sub

    Function GetInstanceDocumentPath(PATH_TO_FILINGS As String)

        'this part launches IE and goes to the correct directory
        If IEbrowser Is Nothing Then
            Set IEbrowser = CreateObject("InternetExplorer.application")
            IEbrowser.Visible = False
        End If

        IEbrowser.Navigate URL:=PATH_TO_FILINGS

        While IEbrowser.Busy Or IEbrowser.readyState <> 4: DoEvents: Wend

       'this part starts the regular expression engine and searches for the reg exp pattern (i.e. the file name)
        Dim RE As Object
        Set RE = CreateObject("vbscript.regexp")

        RE.Pattern = "(?<="[a-zA-Z0-9.-]*\d{8}.xml(?=")"   '"\w+(?=-)(-)\d{8}(.xml)"
        MsgBox RE.Pattern
        RE.IgnoreCase = True

        Dim INSTANCEDOCUMENT As Object

        Set INSTANCEDOCUMENT = RE.Execute(IEbrowser.Document.body.innerhtml)

        If INSTANCEDOCUMENT.Count = 1 Then

            GetInstanceDocumentPath = PATH_TO_FILINGS & "/" & INSTANCEDOCUMENT.Item(0)

        End If

    End Function

感谢您对如何解决此问题的任何想法。

【问题讨论】:

    标签: regex excel vba


    【解决方案1】:

    尝试这样做:

    Sub Test()
    RealQ = Chr(34)
    Pattern = "(?<=" & RealQ & ")[a-zA-Z0-9.-]*\d{8}.xml(?=" & RealQ & ")"
    MsgBox Pattern
    End Sub
    

    结果:

    此外,VBA 不支持后视,但支持前瞻。可以找到更好的参考here

    【讨论】:

    • 是的。这通过了正确的模式。非常感谢。请注意,我发布的代码中有错字。我在所有添加和删除 " 中删除了 ) 以使其正常工作。应该阅读: (?
    • @mchac:编辑了上面的代码以包含缺少的)。此外,请务必检查提供的有关前瞻的链接。 VBScript 不支持lookbehind,这也适用于VBA
    • 啊,对不起,BK。我看到了你的屏幕截图,非常兴奋,我没有继续阅读。现在会这样做。
    • @mchac:刚刚添加了最后一行,所以不用担心。如果您发现此答案有帮助,请将其标记为答案。谢谢!
    • 刚刚标记为答案。再次感谢。我在 RegEx 方面的经验有限,我正在阅读您提供的参考资料,但如果您能在我的情况下建议实施,我将不胜感激。很高兴作为新问题发布
    猜你喜欢
    • 1970-01-01
    • 2012-01-14
    • 2016-01-13
    • 2018-04-03
    • 1970-01-01
    • 2013-01-13
    • 1970-01-01
    • 2017-01-18
    • 2021-09-02
    相关资源
    最近更新 更多