在VB.NET中寻找一种验证逗号分隔的RGB字符串值的方法
数字不能大于 255 ,并且可接受以下格式:
"255,255,255"
"025,25,1"
"0,0,0"
逗号之间的值永远不会有空格,所以这不是问题。
无效:
"256,255,255"
"255,567,255"
"255,,255"
"255,255"
etc
答案 0 :(得分:1)
你可以使用这种模式。它有3个相同的组,匹配0到255之间的数字:
^([0-1]?\d?\d|2[0-4]\d|25[0-5]),([0-1]?\d?\d|2[0-4]\d|25[0-5]),([0-1]?\d?\d|2[0-4]\d|25[0-5])$
答案 1 :(得分:1)
正则表达式不太适合范围验证。我认为更好的解决方案是检查它是否符合一般的逗号分隔格式,然后沿着逗号分割字符串并将值解析为整数。您仍然可以使用正则表达式来防止int解析器在无效格式上失败,例如:
^\d{1,3},\d{1,3},\d{1,3}$
答案 2 :(得分:1)
虽然在表达式中尝试范围验证通常会增加表达式的复杂性,但一个例子是:
^(?:(?:^|,\s*)([01]?\d\d?|2[0-4]\d|25[0-5])){3}$
此表达式查找以下序列重复正好三次:
单独捕获各个元素(R,G,B)(.NET支持在同一个捕获组中进行多次捕获),并且可以像这样访问:
Dim pattern As String = "^(?:(?:^|,\s*)([01]?\d\d?|2[0-4]\d|25[0-5])){3}$"
Dim input As String = "055,5, 0" ' The input to be matched
Dim r As Regex = New Regex(pattern)
Dim m As Match = r.Match(input)
If Not m.Success Then
Console.WriteLine("{0}: Not a match", input)
Else
' Capture red, green, blue elements from the original string
Dim red = CInt(m.Groups(1).Captures(0).Value)
Dim green = CInt(m.Groups(1).Captures(1).Value)
Dim blue = CInt(m.Groups(1).Captures(2).Value)
Console.WriteLine("Color: r={0},g={1},b={2}", red, green, blue)
End If