gpt4 book ai didi

regex - Excel VBA 正则表达式匹配位置

转载 作者:行者123 更新时间:2023-12-02 00:34:48 27 4
gpt4 key购买 nike

如何获取正则表达式中第一个匹配结果的位置?见下文。

Function MYMATCH(strValue As String, strPattern As String, Optional blnCase As Boolean = True, Optional blnBoolean = True) As String
Dim objRegEx As Object
Dim strPosition As Integer

' Create regular expression.
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Pattern = strPattern
objRegEx.IgnoreCase = blnCase

' Do the search match.
strPosition = objRegEx.Match(strValue)

MYMATCH = strPosition
End Function

首先,我不完全确定 .Match 返回什么(字符串、整数等)。我发现的一个解决方案说我应该创建一个 Match 对象,然后从那里获取位置,但与 不同, 无法识别 Match 对象。我也见过some code如下所示,但我不一定要寻找该值,而只是寻找第一个字符串的位置:

If allMatches.count <> 0 Then
result = allMatches.Item(0).submatches.Item(0)
End If

稍微忽略上面任何可能的语法错误(主要是由于我左右更改变量类型),我如何轻松/简单地完成此操作?

谢谢!

最佳答案

您可以使用FirstIndex使用Execute方法返回匹配的位置,即

Function MYMATCH(strValue As String, strPattern As String, Optional blnCase As Boolean = True, Optional blnBoolean = True) As String
Dim objRegEx As Object
Dim strPosition As Integer
Dim RegMC

' Create regular expression.
Set objRegEx = CreateObject("VBScript.RegExp")
With objRegEx
.Pattern = strPattern
.IgnoreCase = blnCase
If .test(strValue) Then
Set RegMC = .Execute(strValue)
MYMATCH = RegMC(0).firstindex + 1
Else
MYMATCH = "no match"
End If
End With
End Function

Sub TestMe()
MsgBox MYMATCH("test 1", "\d+")
End Sub

关于regex - Excel VBA 正则表达式匹配位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8301622/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com