views:

471

answers:

2

I'm attempting to build a function that will return a regex that is dynamically created. The regex to create will be a range check between two numbers. So far I've got something similar to this (not finished as yet).

Is this approach valid, or is there an easier way that I'm overlooking?

Public Shared Function Range(ByVal Minimum As Integer, ByVal Maximum As Integer) As String
Return "^([" & Minimum.ToString.PadLeft(2, "0") & "]" & Microsoft.VisualBasic.StrDup(Minimum.ToString.Length, "[0-9]") & "|2[0-4][0-9]|25[0-5])$"
End Function
+1  A: 

I'd really do this without a regex:

Public Shared Function CheckRange(ByVal valueToCheck As String, ByVal Minimum As Integer, Byval Maximum As Integer) As Boolean
    Dim value As Integer
    If Not Integer.TryParse(valueToCheck, value) Then ''//should include a IFormatProvider as well
         ''//Throw exception!
         Return False
    End If

    Return Minimum <= value AndAlso value <= Maximum
End Function
Joel Coehoorn
I realist that that would be an easier way to do this. For reusability of this particular section of code, I need a regex.Paul.
Paul
+1 - Though I remember that someone here was crazy enough to actually build a function that creates regexes that check integer ranges...
Tomalak
Perhaps a change in design is on the cards. This does seem overly complex for something so simple in regular code.
Paul
A: 

Is the expression to validate the actual range value of the numbers?

If so, you may want to actually capture the values in groups and validate them individually. RegEx is for evaluating strings, not numbers, so for example...

Regex.Match(str, "^[10-20]$") //isn't going to match for 15

By capturing groups use this as an example...

Dim value As String = "Value:45"
Dim str As String = Regex.Match(value, "^Value:(?<value>\d+)$").Groups("value").Value

//str should be "45", which now you can parse as an integer
Integer.TryParse(...etc...
Hugoware
It is to validate the actual range values. Yep and Eek.
Paul