RegEx端口枚举验证

时间:2012-11-04 17:32:07

标签: c# .net regex

我是正则表达式的新手,请帮我写一个新的正则表达式。它应该适用于这些:

28
28,57,130
13-18
13,18-57,65
44-56,50-130,150,180-213
12-25,28
1024-8000,27000-30000
1024-65535

它不适用于

15,13 // 13 is less than 15
15-11 // 11 is less than 15
15-18,10
15-18,20,11-130 // because of 11
0 // port number 0 is reserved and can't be used 
11-180,250,65536 // it should be less than 65535

1 个答案:

答案 0 :(得分:2)

使用regex会使其更复杂..

您可以regex使用parse,而不是使用bool matchIt(string input)//returns true|false for a match { if(input=="0")return false;//cuz you dont want to match 0 string[] parts=input.Split(new char[] { ',','-' }, StringSplitOptions.None);//split them int prev=int.Parse(parts[0]); foreach(string s in parts) { if(prev>int.Parse(s))return false; prev=int.Parse(s); } return true; }

{{1}}