Lea*_*ing 1 regex macros vbscript vba word-vba
我需要获取子匹配字符串的索引位置值。根据文档,我已经阅读了此正则表达式并了解了FirstIndex属性以获取匹配字符串的位置。
但这仅适用于一维匹配的字符串。我无法申请子FirstIndex比赛。请参考样本匹配
我尝试过这种格式,
Dim myRegExp As Object, match As MatchCollection
Dim matched As String
Set myRegExp = CreateObject("VBScript.RegExp")
myRegExp.pattern = find
If myRegExp.test(text) = True Then
Set match = myRegExp.Execute(text)
Debug.Print match(0).submatches(0) '' this is matched string
Run Code Online (Sandbox Code Playgroud)
我应该在哪里打电话FirstIndex以获得匹配的字符串的位置
输出:
match(0)=>Berry, Brent. (2006). What accounts for race and ethnic differences in Berry,
Brent. parental financial transfers to adult children in the United States? Journal of Family
Issues 37:1583-1604.
submatches(0)=>Berry, Brent.
submatches(6)=>2006
Run Code Online (Sandbox Code Playgroud)
预期的输出:
submatches(0) at 0th position
submatches(6) at 16th position and so on
Run Code Online (Sandbox Code Playgroud)
您无法申请.FirstIndex,SubMatches(x)因为它返回String,而不是Match。如果组将返回唯一的匹配项,则只需使用以下Instr函数即可找到其位置:
With CreateObject("VBScript.RegExp")
.Pattern = Find
If .Test(text) Then
Set match = .Execute(text)
Debug.Print InStr(1, text, match(0).SubMatches(0)) '0
Debug.Print InStr(1, text, match(0).SubMatches(5)) '16
'and so on
End If
End With
Run Code Online (Sandbox Code Playgroud)
如果各组将不会返回唯一的结果,则可以跟踪上一个匹配项的位置并遍历结果。请注意,VBScript.RegExp它不支持回溯,因此您不必考虑匹配的长度:
With CreateObject("VBScript.RegExp")
.Pattern = find
If .Test(text) Then
Set match = .Execute(text)
Dim i As Long, pos As Long, found As String
pos = 1
For i = 0 To match(0).SubMatches.Count - 1
found = match(0).SubMatches(i)
pos = InStr(pos, text, match(0).SubMatches(i))
Debug.Print found, pos
Next
End If
End With
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5016 次 |
| 最近记录: |