【问题标题】:get ASCII value of a Regex backreference in VBA在 VBA 中获取正则表达式反向引用的 ASCII 值
【发布时间】:2011-08-16 16:39:55
【问题描述】:

我在 VBA 中有以下 sn-p

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!"

我想用它的 ascii 值替换每个正则表达式匹配 - 在这种情况下,用它的 ascii 值替换任何不是字母或数字的东西,所以结果字符串应该是

"Hello44 World33"

我基本上想要这样的东西在反向引用上使用 Asc() 函数:

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

除非那是无效的。我试过用各种方法逃跑,但我想我找错树了。

谢谢!

【问题讨论】:

    标签: regex vba ascii


    【解决方案1】:

    不知道您是否可以使用 Replace() 一次性完成,但您可以使用 Execute() 并循环匹配。请注意,您的原始模式也匹配 |,我认为您不需要。

    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
    

    【讨论】:

    • 完美,蒂姆,谢谢!顺便说一句,我使用管道作为“或”分隔符,但我想这不是必需的。再次感谢。
    【解决方案2】:

    Regex.Replace 的签名之一采用评估器而不是替换值的字符串。看看这个:

    Replace Method (String, MatchEvaluator)

    如果您需要进一步的帮助,请告诉我。


    编辑:添加了实际代码。

    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
    

    【讨论】:

    • 看起来不错,但比下面蒂姆的回答要冗长一些。不过谢谢!
    • @MisterCoffee - 我添加了实际代码。代码简洁明智,我认为它们很相似。
    猜你喜欢
    • 2012-11-18
    • 1970-01-01
    • 2017-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-28
    • 2018-07-13
    • 1970-01-01
    相关资源
    最近更新 更多