构建动态正则表达式

时间:2009-06-12 12:46:29

标签: vb.net regex dynamic

我正在尝试构建一个返回动态创建的正则表达式的函数。要创建的正则表达式将是两个数字之间的范围检查。到目前为止,我有类似的东西(尚未完成)。

这种方法有效,还是有一种我更容易忽视的方式?

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

2 个答案:

答案 0 :(得分:1)

如果没有正则表达式,我真的会这样做:

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

答案 1 :(得分:0)

表达式是否验证数字的实际范围值?

如果是这样,您可能希望实际捕获组中的值并单独验证它们。 RegEx用于评估字符串,而不是数字,例如......

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

通过捕获组,以此为例......

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...