2011-08-16 35 views
2
正則表達式反向引用的ASCII值

我在VBA獲得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!" 

我想它的ASCII值來代替每個正則表達式匹配下面的代碼片段 - 在這種情況下,更換任何東西,這不是一個字母或其ASCII值數,因此所得到的字符串應該是

"Hello44 World33" 

我基本上想要的東西,像這樣使用Asc()函數在一個反向引用:

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

除外無效。我嘗試過以各種方式逃避,但我認爲我在吠叫錯誤的樹。

謝謝!

回答

0

不知道你是否能一氣呵成替換爲()做到這一點,但你可以通過比賽使用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 
+0

完美,蒂姆,謝謝!順便說一句,我使用管道作爲「或」分隔符,但我想這不是要求。再次感謝。 – MisterCoffee

0

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 
+0

看起來很不錯,但比Tim的回答略低一些。不過謝謝! – MisterCoffee

+0

@MisterCoffee - 我添加了實際的代碼。代碼簡單明智,我認爲他們是相似的。 –

+0

是的,確實如此。謝謝。 – MisterCoffee