1

您好,此代码由 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
4

1 回答 1

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
于 2013-07-12T15:34:51.393 回答