Skip to content

Add a function that converts a string into .NET-compatible, escaped RegEx #9

Open
@franklesniak

Description

@franklesniak

For example:

Function ConvertToDotNetEscapedRegEx(ByVal strInputString)
    Dim arrRegexCharactersToEscapeWithBackslash
    Dim strEscapedString
    Dim intCounterA

    ' Source: https://learn.microsoft.com/en-us/dotnet/standard/base-types/character-escapes-in-regular-expressions
    ' Also verified through testing in PowerShell
    arrRegexCharactersToEscapeWithBackslash = Array("\", ".", "$", "^", "{", "[", "(", "|", ")", "*", "+", "?", "#", " ")

    strEscapedString = strInputString
    
    For intCounterA = 0 To UBound(arrRegexCharactersToEscapeWithBackslash)
        strEscapedString = Replace(strEscapedString, arrRegexCharactersToEscapeWithBackslash(intCounterA), "\" & arrRegexCharactersToEscapeWithBackslash(intCounterA))
    Next

    ' strEscapedString = Replace(strEscapedString, Chr(7), "\a") ' Not necessary; PowerShell 7.2.x on Windows 11 does not encode this character
    ' strEscapedString = Replace(strEscapedString, Chr(8), "\b") ' Not necessary; PowerShell 7.2.x on Windows 11 does not encode this character
    strEscapedString = Replace(strEscapedString, vbTab, "\t") ' Chr(9)
    ' strEscapedString = Replace(strEscapedString, vbCrLf, "\n")
    strEscapedString = Replace(strEscapedString, vbLf, "\n") ' Chr(10)
    ' strEscapedString = Replace(strEscapedString, Chr(11), "\v") ' Not necessary; PowerShell 7.2.x on Windows 11 does not encode this character
    strEscapedString = Replace(strEscapedString, Chr(12), "\f") ' Chr(12)
    strEscapedString = Replace(strEscapedString, vbCr, "\r") ' Chr(13)
    ' strEscapedString = Replace(strEscapedString, Chr(18), "\e") ' Not necessary; PowerShell 7.2.x on Windows 11 does not encode this character

    ConvertToDotNetEscapedRegEx = strEscapedString
End Function

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions