How to extract ad sizes from a string with excel regex

前端 未结 3 1017
野性不改
野性不改 2021-01-24 15:52

I am trying to extract ad sizes from string. The ad sizes are all set standard sizes. So while I\'d prefer to have a regex that looks for a pattern, IE 3 numbers followed by 2 o

3条回答
  •  臣服心动
    2021-01-24 16:22

    EDIT: Since it's not actually underscore delimited we can't use Split. We can however iterate over the string and extract the "#x#" manually. I have updated the code to reflect this and verified that it works successfully.

    Public Function ExtractAdSize(ByVal arg_Text As String) As String
    
        Dim i As Long
        Dim Temp As String
        Dim Ad As String
    
        If arg_Text Like "*#x#*" Then
            For i = 1 To Len(arg_Text) + 1
                Temp = Mid(arg_Text & " ", i, 1)
                If IsNumeric(Temp) Then
                    Ad = Ad & Temp
                Else
                    If Temp = "x" Then
                        Ad = Ad & Temp
                    Else
                        If Ad Like "*#x#*" Then
                            ExtractAdSize = Ad
                            Exit Function
                        Else
                            Ad = vbNullString
                        End If
                    End If
                End If
            Next i
        End If
    
    End Function
    

    Alternate version of the same function using Select Case boolean logic instead of nested If statements:

    Public Function ExtractAdSize(ByVal arg_Text As String) As String
    
        Dim i As Long
        Dim Temp As String
        Dim Ad As String
    
        If arg_Text Like "*#x#*" Then
            For i = 1 To Len(arg_Text) + 1
                Temp = Mid(arg_Text & " ", i, 1)
    
                Select Case Abs(IsNumeric(Temp)) + Abs((Temp = "x")) * 2 + Abs((Ad Like "*#x#*")) * 4
                    Case 0: Ad = vbNullString       'Temp is not a number, not an "x", and Ad is not valid
                    Case 1, 2, 5: Ad = Ad & Temp    'Temp is a number or an "x"
                    Case 4, 6: ExtractAdSize = Ad   'Temp is not a number, Ad is valid
                               Exit Function
                End Select
            Next i
        End If
    
    End Function
    

提交回复
热议问题