Tuesday 13 June 2023

RegEx in EXCEL

' @info: function find server name "xx00x00x" from give string at the begining of string or srever name begin with space
' @return: string | name of server
Public Function getServer(str As String) As String
On Error GoTo Err_getServer
    Dim regex As Object
    Set regex = CreateObject("VBScript.RegExp")
     
    With regex
        .Pattern = "^(\s*)[A-Z][A-Z][0-9][0-9][A-Z][0-9][0-9][A-Z]*|\s[A-Z][A-Z][0-9][0-9][A-Z][0-9][0-9][A-Z]*"
        .IgnoreCase = True
        .Global = True
    End With
 
    Set matches = regex.Execute(str)
     
    For Each Match In matches
        Debug.Print Match.Value '
        getServer = getServer + Match.Value
    Next Match
     
    'remove space
    getServer = Replace(getServer, " ", "", 1, 1)
     
Ext_getServer:
    Exit Function
 
Err_getServer:
   getServer = CVErr(xlErrValue)
   GoTo Ext_getServer
End Function


' @info: function find server name "xx00x00x" from give string at the begining of string or srever name begin with space in string and replace with ""
' @return: string | clear string with out server name
Public Function getClearStr(str As String) As String
On Error GoTo Err_getClearStr
    Dim regex As Object
    Dim temp As String
    Set regex = CreateObject("VBScript.RegExp")
       
    With regex
        .Pattern = "^(\s*)[A-Z][A-Z][0-9][0-9][A-Z][0-9][0-9][A-Z]*|\s[A-Z][A-Z][0-9][0-9][A-Z][0-9][0-9][A-Z]*"
        .IgnoreCase = True
        .Global = True
    End With
   
    Set matches = regex.Execute(str)
       
    For Each Match In matches
        Debug.Print Match.Value '
        temp = Match.Value
    Next Match
   
    getClearStr = Replace(str, temp, "", 1, 1)
   
    If (Left(getClearStr, 1) = ";") Or (Left(getClearStr, 1) = ",") Then
        If Len(getClearStr) > 1 Then
            getClearStr = Right(getClearStr, Len(getClearStr) - 1)
        End If
    End If
   
Exit_getClearStr:
    Exit Function
   
Err_getClearStr:
    getClearStr = CVErr(xlErrValue)
    GoTo Exit_getClearStr
End Function

No comments:

Post a Comment