首页 /编程语言和算法/VB6/VBA/ASP
 VBA代码 正则标准函数 mRegex
2025年3月18日 14:49
Function regMatch(ByVal s, pString)    '返回正则匹配的集合
    Dim regex As Object, matchs
    Dim temp, n
    Set regex = CreateObject("VBScript.RegExp")
    With regex
        .Global = True
        .IgnoreCase = True
        .Pattern = pString
        Set matchs = .Execute(s)
    End With
    Set regex = Nothing
    Set regMatch = matchs
    Set matchs = Nothing
End Function

Function regReplace(s, pstrt, rstr)    '正则替换
    Dim regex As Object
    Dim temp
    Set regex = CreateObject("VBScript.RegExp")
    With regex
        .Global = True
        .Pattern = pstrt
        temp = .Replace(s, rstr)
    End With
    regReplace = temp
    Set regex = Nothing
End Function

Public Function regGet(s, pString, Optional m = 0, Optional sp = "")
    '返回正则匹配\d[^_]*\d
    'm-是否多个
    'sp-分隔符
    Dim matchs, regex
    Dim ss, n
    Set regex = CreateObject("VBScript.RegExp")
    With regex
        .Global = True
        .IgnoreCase = True
        .Pattern = pString
        Set matchs = .Execute(s)
    End With
    If matchs.Count = 0 Then
        regGet = ""
    Else
        If m = 0 Then    '取第一个值
            regGet = matchs(0).Value
        Else    '取多个值
            For Each e In matchs
                ss = ss & sp & e.Value
            Next
            regGet = Mid(ss, Len(sp) + 1)
        End If
    End If
    Set regex = Nothing
    Set matchs = Nothing
End Function

Public Function regTest(s, pString)    '返回正则匹配\d[^_]*\d
    Dim matchs, regex
    Dim temp, n
    Set regex = CreateObject("VBScript.RegExp")
    With regex
        .Global = True
        .IgnoreCase = True
        .Pattern = pString
        regTest = .Test(s)
    End With
    Set regex = Nothing
    Set matchs = Nothing
End Function



 
全部回复(0)
首页 | 电脑版 |