excelregexdatabasedata-conversion

Mapping logic for converting a pattern in excel or database


I have thousands of mapping pattern that I need to convert. Attached is the image which shows the source value which I need to convert into Target values.

Source Pattern vs Target Pattern

Few of the rules that I am able to decipher are below: -

  1. If the dash ('-') is just before any value then it needs to convert to pipe ('|')
  2. If there are multiple dashes in the middle e.g. 4 dashes, then they would converted to 4 pipes and 3 dashes as shown in second example in order to show 3 empty fields (|-|-|-|)
  3. If there are multiple dashes at the end e.g. 3 dashes, then they would be converted to 3 pipes and 3 dashes as shown in first example in order to show 3 empty fields without pipe at the end (|-|-|-)
  4. There would never be a dash at the beginning
  5. There are in total 8 values. Each |-| is considered a empty value. Each field is separated by pipe.

I am looking at ways to convert the source values into intended target values using any software possible.


Solution

  • This quick user defined function appears to meet your requirements without regular expressions.

    Function mapSource(str As String)
    
        Dim tmp As Variant, i As Long
    
        'strip leading hyphens
        Do While Left(str, 1) = Chr(45) And Len(str) > 0: str = Right(str, Len(str) - 1): Loop
    
        'split str to a maximum of 8 array elements
        tmp = Split(str, Chr(45), 8)
    
        'preserve an array of 8 elements
        ReDim Preserve tmp(7)
    
        'replace empty array elements with hyphens
        For i = LBound(tmp) To UBound(tmp)
            If tmp(i) = vbNullString Then tmp(i) = Chr(45)
        Next i
    
        'rejoin array into str
        str = Join(tmp, Chr(124))
    
        'output mapped str
        mapSource = str
    
    End Function
    

    enter image description here