Romz
Romz

Reputation: 1457

RegEx port enumeration validation

I'm new to Regular Expressions, please help me to write a new Regex. It should be working for these:

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

It shoudn't work for

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

Upvotes: 0

Views: 240

Answers (1)

Anirudha
Anirudha

Reputation: 32817

Using regex for this would make it more complicated..

Instead of using regex you can parse it like this

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;
}

Upvotes: 2

Related Questions