使用RegEx获取输入页面的错误处理

时间:2013-07-12 15:24:27

标签: regex vb.net error-handling

  

你好这段代码是Chris,结合MackieChan解决方案

查看我丢失的代码,我无法弄清楚如何添加范围。

我的意思是:

我正在尝试更改或更新代码,以检测页面的逗号,

以下代码显示了如何使用逗号输入页面

示例:1,2,5,3,8并且它不接受0或大于最大页面

我要问的是添加可以接受的代码:

2-5,8,9 要么 8,9,2-5 所以这意味着,要打印的页面是2,3,4,5,8,9

或 2,4-6,9,8 所以这意味着,要打印的页面是2,4,5,6,8,9

private rgxNumberWithComma As New System.Text.RegularExpressions.Regex("^([0-9]+,?)+$")
Public Function CheckInput(ByVal valyo As String, _
             ByVal origMaxPage As Integer) As Boolean

Dim match = rgxNumberWithComma.Match(valyo)
If Not match.Success Then
    Return False
Else
    Dim numbers as new List(Of Integer) ‘will store added numbers
    For Each Item In valyo.Split(","c)
        Dim intValue As Integer
        ‘Check if number is a valid integer
        ‘Check if number is 0
        ‘Check if number has already added the number list
        ‘Check if number is greater that MaxPage
        If Not Integer.TryParse(Item, intValue) _
                   OrElse intValue > origMaxPage _
                   OrElse intValue = 0 _
                   OrElse numbers.Contains(IntValue) Then
            Return False
        Else
            ‘Item is valid, continue
            Numbers.Add(intValue)    
        End If
    Next
End If
Return True
End Function

1 个答案:

答案 0 :(得分:1)

您可以使用它来验证字符串:

^[0-9]+(-[0-9]+)?(,[0-9]+(-[0-9]+)?)+$

这也将确保字符串不以逗号开头或结尾。

为了评估字符串,我建议:

Dim numbers as new List(Of Integer) ‘will store added numbers
For Each Item In valyo.Split(","c)
    Dim parts = Item.Split("-"c)
    If parts.Length > 1 Then
        ‘Evaluate range
        Dim minValue As Integer
        Dim maxValue As Integer
        If Not Integer.TryParse(Item, minValue) _
                   OrElse Not Integer.TryParse(Item, maxValue) _
                   OrElse minValue > maxValue _
                   OrElse maxValue > origMaxPage _
                   OrElse minValue = 0 Then
            Return False
        Else
            For value As Integer = minValue To maxValue 
                If numbers.Contains(value) Then
                    Return False
                End If

                ‘Item is valid, continue
                numbers.Add(value)
            Next
        End If
    Else
        Dim intValue As Integer
        If Not Integer.TryParse(Item, intValue) _
                   OrElse intValue > origMaxPage _
                   OrElse intValue = 0 _
                   OrElse numbers.Contains(IntValue) Then
            Return False
        Else
            ‘Item is valid, continue
            numbers.Add(intValue)    
        End If
    End If
Next