Click here to Skip to main content
15,898,371 members
Please Sign up or sign in to vote.
5.00/5 (1 vote)
See more:
Hi all,

I am using C#.Net 2008.

I am using following code to varify proper format (udp ip:port i.e "225.1.1.1:3000") of input string.
But it is not working properly.


System.Text.RegularExpressions.Regex regStr = new System.Text.RegularExpressions.Regex(@"\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:\d{1,5}");

bool b;
b = regStr.IsMatch("225.1.1.1:3000"); //return true
b = regStr.IsMatch("2225.1.1.1:3000"); //return true. should return false

Anybody knows proper regular expression for ip:port format?
Can anyone give me good links for using Regex , regular expression in C#.

Thanks in advance.

Regards,
Aniket A. Salunkhe
Posted

This behavior is correct, because the regexp you wrote checks for matches contained in the input string.
If you want to match the whole string only, you must add ^ at the begin and $ at the end of your regex.

For Example: "^\d{1,3}.\d{1,3}.\d{1,3}.\d{1,3}:\d{1,5}$"
 
Share this answer
 
Though this is quite an old post, I thought it'll be worthwhile to add the following for future reference:

Both above regex patterns will also return true for
225*1*1*1:3000 or
225a1b1c1:3000 etc. This is because you're not using the literal "." in your pattern. Therefore, escaping the "."s in the above pattern would be a good idea, like so:
@"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}$"

so that the literal "." character is not confused with the "." metacharacter for regular expressions.
 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900