开发者

get ASCII value of a Regex backreference in VBA

开发者 https://www.devze.com 2023-03-28 06:34 出处:网络
I have the following snippet in VBA Dim RegEx As Object Dim myResult As String Set RegEx = CreateObject(\"vbscript.regexp\")

I have the following snippet in VBA

Dim RegEx As Object
Dim myResult As String

Set RegEx = CreateObject("vbscript.regexp")
With RegEx
    .Global = True
  开发者_运维问答  .IgnoreCase = True
    .MultiLine = True
    .Pattern = "([^a-z|A-Z|0-9|\s])"
End With

myResult = "Hello, World!"

I want to replace each regex match with its ascii value -- in this case, replace anything that's not a letter or number with its ascii value, so the resulting string should be

"Hello44 World33"

I basically want something like this to use the Asc() function on a backreference:

myResult = RegEx.Replace(myResult, Asc("$1"))

except that's not valid. I've tried escaping in various ways but I think I am barking up the wrong tree.

Thanks!


Don't know if you can do it in one go with Replace(), but you can use Execute() and loop through the matches. Note your original pattern also matched |, which I don't think you wanted.

Sub Tester()
    Dim RegEx As Object, matches As Object, match As Object
    Dim myResult As String

    Set RegEx = CreateObject("vbscript.regexp")
    With RegEx
     .Global = True
     .IgnoreCase = True
     .MultiLine = True
     .Pattern = "([^a-z0-9\s])"
    End With

    myResult = "Hello, World!"

    Set matches = RegEx.Execute(myResult)
    For Each match In matches
        Debug.Print "<" & match.Value & "> = " & Asc(match.Value)
        myResult = Replace(myResult, match.Value, Asc(match.Value))
    Next match
    Debug.Print myResult

End Sub


One of the signatures of Regex.Replace takes an evaluator instead of a string for the replacement value. Take a look at this:

Replace Method (String, MatchEvaluator)

Let me know if you need further help.


Edit: Added the actual code.

Imports System
Imports System.Text.RegularExpressions

Module RegExSample

    Function AscText(ByVal m As Match) As String
        Return Asc(m.ToString())
    End Function

    Sub Tester()
        Dim RegEx As Object, matches As Object, match As Object
        Dim myResult As String

        Set RegEx = CreateObject("vbscript.regexp")
        With RegEx
         .Global = True
         .IgnoreCase = True
         .MultiLine = True
         .Pattern = "([^a-z0-9\s])"
        End With

        myResult = "Hello, World!"

        myResult = RegEx.Replace(text, AddressOf RegExSample.AscText)
        Debug.Print myResult

    End Sub

End Module
0

精彩评论

暂无评论...
验证码 换一张
取 消