2014-10-30 83 views
0

我正在寫一個函數來格式化字符串。我收到一串數字,有時候是破折號,有時候不是。我需要產生一個14個字符的輸出字符串,所以如果輸入字符串包含少於14個字符,我需要填充零。那麼我需要通過在適當的位置插入破折號來掩蓋數字串。這是我到目前爲止:字符串掩碼 - 插入破折號

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 

上述工作正常,除了它只是返回一個數字的字符串,而不是在破折號。我知道我在做String.Format錯誤,但到目前爲止我只使用預定義的格式。誰能幫忙?在這種情況下,我如何使用正則表達式來進行字符串格式化?

回答

1

這個功能應該做的伎倆:

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 

你可以找到更多關於字符串格式化here