增加字符串中的数字并将其填充为零

时间:2011-03-25 15:26:27

标签: regex vb.net string

在VB.NET中,我想在字符串中增加一个数字并将其填充为零。

以下是5位数字的示例字符串:
R00099

在将它递增一之后我想要返回的内容:
R00100

4 个答案:

答案 0 :(得分:10)

无需PadLeft

Dim result = String.Format("R{0:D5}", number)

格式化程序中的D5部分会将数字格式化为十进制数字,使用固定的五位数字,并用零填充冗余数字。

有关decimal format specifier

的MSDN文章可以找到更多信息

答案 1 :(得分:1)

假设(使用正则表达式标记)首先要删除数字,输入将始终采用字母后跟数字的形式:

Function Increment(ByVal prefixedNumber As String) As String
    Dim result As String = String.Empty
    Dim numericRegex As New Text.RegularExpressions.Regex("^(\D*)(\d*)")
    Dim numericMatch As Text.RegularExpressions.Match = numericRegex.Match(prefixedNumber)

    If numericMatch.Success Then
        Dim number As Integer

        If Integer.TryParse(numericMatch.Groups(2).Value, number) Then
            result = String.Format("{0}{1:D5}", numericMatch.Groups(1).Value, number + 1)
        Else
            ' throw a non parse exception.
        End If
    Else
        ' throw a non match exception.
    End If

    Return result
End Function

查看RegexInteger.TryParse文档

答案 2 :(得分:1)

如果字符串已经过验证并且采用指定的格式,那么这应该可以正常工作

Private Function add1ToStringNoChecking(theString As String) As String
    'assumes many things about the input instring
    Return String.Format("{0}{1:d5}", _
                                        "R", _
                                        CInt(theString.Substring(theString.Length - 5, 5)) + 1)
End Function

Private Sub Button1_Click(sender As System.Object, _
                          e As System.EventArgs) Handles Button1.Click
    Dim testS As String = "R00009"
    Debug.WriteLine(add1ToStringNoChecking(testS))
End Sub

答案 3 :(得分:-2)

这是一个实现OP要求的便利功能:

    Public Function Counter(ByVal StartingNumber As Int32, ByVal IncrementValue As Int32, ByVal TotalNumberLength As Int32, ByVal Prefix As String) As String
        Dim Temp As Int32 = StartingNumber + IncrementValue
        Dim Temp2 As String = CStr(Temp)

Line50:
        If Temp2.Length < TotalNumberLength Then
            Temp2 = "0" & Temp2
            GoTo Line50
        ElseIf Temp2.Length = TotalNumberLength Then
            'do nothing
        Else
            'means error
            Throw New System.Exception()
        End If

        Return Prefix & Temp2

    End Function

使用该功能的例子:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    'now test the function
    MessageBox.Show(Counter(99, 1, 5, "R"))

    'it will show R00100    
End Sub

注意:此解决方案已经过Visual Studio 2010测试。