正则表达式 Return 位置 VBA
Regexp Return position VBA
我正在寻找正则表达式 return 我正在寻找的模式或位置的值。类似于 Instr 函数的工作方式 returning 它在字符串中的位置我希望能够使用模式来做到这一点。到目前为止我所拥有的只是替换了模式,我不知道如何让它 return 一个位置。
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
如果您不想替换而只想获取命中的位置,请使用Execute
-方法。它 returns 一组火柴。匹配基本上具有三个属性:
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
我正在寻找正则表达式 return 我正在寻找的模式或位置的值。类似于 Instr 函数的工作方式 returning 它在字符串中的位置我希望能够使用模式来做到这一点。到目前为止我所拥有的只是替换了模式,我不知道如何让它 return 一个位置。
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
如果您不想替换而只想获取命中的位置,请使用Execute
-方法。它 returns 一组火柴。匹配基本上具有三个属性:
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