我希望我的正則運算式回傳我正在尋找的模式的值或位置。類似于 Instr 函式回傳其在字串中的位置的作業方式,我希望能夠使用模式來執行此操作。到目前為止,我所擁有的只是替換了模式,我無法弄清楚如何讓它回傳一個位置。
Sub test
Dim regex As Object
Dim r As Range, rC As Range
Dim firstextract As Long
' cells in column A
Set r = Range("A2:A3")
Set regex = CreateObject("VBScript.RegExp")
regex.Pattern = "[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]"
' loop through the cells in column A and execute regex replace
Dim MyArray(10, 10) As Integer
For CntMtg = 1 To 100
For Each rC In r
If rC.Value <> "" Then rC.Value = regex.Replace(rC.Value, "Extract from here")
Next rC
Next
End sub
uj5u.com熱心網友回復:
如果您不想替換而只想獲取命中的位置,請使用Execute- 方法。它回傳一個匹配集合。匹配基本上具有三個屬性:
FirstIndex匹配在字串
Length中的位置 找到的匹配的長度 找到
Value的匹配本身
如果一個字串中有多個匹配項,則需要設定Global正則運算式的屬性,否則集合最多會找到 1 個匹配項。
以下代碼使用早期系結(因為它有助于找出屬性和方法),添加對Microsoft VBScript Regular Expressions 5.5的參考。
Dim regex As RegExp
regex.Pattern = "[0-9][0-9]/[0-9][0-9]/[0-9][0-9][0-9][0-9]"
regex.Global = True
Dim matches As MatchCollection, match As match
Set matches = regex.Execute(s)
For Each match In matches
Debug.Print "Pos: " & match.FirstIndex & " Len: " & match.Length & " - Found: " & match.Value
Next
詳情見官方檔案:https ://docs.microsoft.com/en-us/dotnet/standard/base-types/the-regular-expression-object-model
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/458779.html
