Coding Duchess
Coding Duchess

Reputation: 6919

String masking - inserting dashes

I am writing a function to format a string. I receive a string of numbers, sometimes with dashes, sometimes not. I need to produce an output string of 14 characters, so if the input string contains less than 14, I need to pad it with zeros. then I need to mask the string of numbers by inserting dashes in appropriate places. Here is what I got so far:

strTemp = strTemp.Replace("-", "")
If IsNumeric(strTemp) Then

     If strTemp.Length < 14 Then
         strTemp = strTemp.PadRight(14 - strTemp.Length)
     End If

     output = String.Format(strTemp, "{00-000-0-0000-00-00}")
End If

The above works fine, except it just returns a string of numbers without putting in the dashes. I know I am doing something wrong with String.Format but so far I've only worked with pre-defined formats. Can anyone help? How can I use Regex for string formatting in this case?

Upvotes: 0

Views: 668

Answers (1)

Stijn
Stijn

Reputation: 2060

This function should do the trick:

Public Function MaskFormat(input As String) As String
    input = input.Replace("-", String.Empty)

    If IsNumeric(input) Then
        If input.Length < 14 Then
            input = input.PadRight(14 - input.Length)
        End If

        Return String.Format("{0:00-000-0-0000-00-00}", CLng(input))
    Else
        Return String.Empty
    End If
End Function

You can find more on String formatting here.

Upvotes: 1

Related Questions