查看: 24  |  回复: 0
  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


您需要登录后才可以回帖 登录 | 立即注册
【本版规则】请勿发表违反国家法律的内容,否则会被冻结账号和删贴。
用户名: 立即注册
密码:
2020-2025 MaNongKu.com