VB NET正则表达式匹配数字子串

时间:2015-02-24 10:53:36

标签: regex vb.net

我正在尝试创建一个vb函数,它将String作为输入并返回(如果存在)由数字开头直到第一个非数字字符串的字符串,所以:

123 -> 123
12f -> 12
12g34 -> 12
f12 -> ""
"" -> ""

我写了一个函数,逐步比较匹配正则表达式的结果,但它甚至在非数字字符上继续...

这是功能:

Public Function ParseValoreVelocita(ByVal valoreRaw As String) As String

        Dim result As New StringBuilder
        Dim regexp As New Regex("^[0-9]+")
        Dim tmp As New StringBuilder
        Dim stringIndex As Integer = 0
        Dim out As Boolean = False

        While stringIndex < valoreRaw.Length AndAlso Not out
            tmp.Append(valoreRaw.ElementAt(stringIndex))
            If regexp.Match(tmp.ToString).Success Then
                result.Append(valoreRaw.ElementAt(stringIndex))
                stringIndex = stringIndex + 1
            Else
                out = True
            End If
        End While

        Return result.ToString

    End Function

输出总是等于输入字符串,所以有些错误,我无法摆脱它......

3 个答案:

答案 0 :(得分:3)

这是一个不需要正则表达式并提高可读性的LINQ解决方案:

Dim startDigits = valoreRaw.TakeWhile(AddressOf Char.IsDigit)
Dim result As String = String.Concat(startDigits)

答案 1 :(得分:0)

试试这个。您需要使用捕获组:

Public Function ParseValoreVelocita(ByVal valoreRaw As String) As String

    Dim result As New StringBuilder
    Dim regexp As New Regex("^([0-9]+)")
    Dim tmp As New StringBuilder
    Dim stringIndex As Integer = 0
    Dim out As Boolean = False

    While stringIndex < valoreRaw.Length AndAlso Not out
        tmp.Append(valoreRaw.ElementAt(stringIndex))
        If regexp.Match(tmp.ToString).Success Then
            result.Append(regexp.Match(tmp.ToString).Groups(1).Value)
            stringIndex = stringIndex + 1
        Else
            out = True
        End If
    End While

    Return result.ToString

End Function

表达式:

Dim regexp As New Regex("^([0-9]+)")

并且结果附加行已更新:

result.Append(regexp.Match(tmp.ToString).Groups(1).Value)

答案 2 :(得分:0)

对于一项简单的任务,您的代码非常复杂。

你的循环一直在尝试构建一个更长的字符串,它会不断检查它是否仍在使用数字,如果是,则继续追加结果。

所以输入字符串&#34; 123x&#34;如果你的代码有效,会产生一串&#34; 112123&#34;作为输出。换句话说,它匹配&#34; 1&#34;,然后&#34; 12&#34;,然后&#34; 123&#34;并在它们找到&#34; x&#34后退出之前连接每个;

这是你应该做的事情:

Public Function ParseValoreVelocita(valoreRaw As String) As String
    Dim regexp As New Regex("^([0-9]+)")
    Dim match = regexp.Match(valoreRaw)
    If match.Success Then
        Return match.Groups(1).Captures(0).Value
    Else
        Return ""
    End If
End Function

没有循环,你让正则表达式完成工作。