在Excel中转​​义Regex的字符串

时间:2014-03-17 12:49:21

标签: regex excel vba

我正在尝试在Excel单元格中找到关键字。

Function findString(pattern As String, haystack As String)

    Dim RegEx As Object
    Dim strTest As String
    Dim valid As Boolean
    Dim Matches As Object

    Dim found As Boolean

    Set RegEx = CreateObject("VBScript.RegExp")

    ' Initialise Regex object
    With RegEx
        '.Global = False
        .IgnoreCase = True
        .MultiLine = True
    End With

    ' I need something like this here:        
    'RegEx.pattern = RegEx.Escape(pattern)
    RegEx.pattern = pattern

    'return value
    findString = RegEx.test(haystack)

    Set RegEx = Nothing

End Function

pattern是关键字。 但是,此关键字可以包含特殊字符。示例:D | Sign 这应该转移到" D \ | Sign"在执行正则表达式之前。

如何转义此字符串,以便只找到包含输入字符串的单元格?

1 个答案:

答案 0 :(得分:0)

没有明显的逃避功能,我建议你写一个......

将所有字符转义为其Unicode值。

迭代每个输入字符并通过AscW获取Unicode字符值,并在其前面添加\u

因此字符串Aa看起来像\u0065\u0097