0

I have an issue with regular expression. I need to validate for the following url

http://50.244.41.23/ 

http://myserver/

I have used following expressions

Regex urlRx = new Regex(@"(http|https)://([0-9]*)", RegexOptions.IgnoreCase);

Regex urlRx = new Regex(@"(http|https)://(\b(?:\d{1,3}\.){3}\d{1,3}\b)", RegexOptions.IgnoreCase);

Both are working up to an extent, But it doesn't serve the exact purpose. It gives success for the following strings, But i want the expression to fail for such strings..

http://50.244.41.23\

http://256.244.41.23/

http://256.244.41.23.123/

Can someone help to create an apt regex validation for the above url.

Thanks Sebastian

2 Answers 2

1

Here are some example regexes for matching IPv4 addresses; the "Accurate" versions only match valid addresses: http://answers.oreilly.com/topic/318-how-to-match-ipv4-addresses-with-regular-expressions/

By adding a little more, you should be able to match URLs in the form you're looking for. This should match your first (valid) IP address in your question, but not the last (invalid) 3:

^https?://(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)/$

Sign up to request clarification or add additional context in comments.

1 Comment

I want to validate the port also, for e.g. 50.244.41.23:8085... What need to be changed?
0

By using the tokens for the beginning (^) and end of the line ($), you can ensure that your match is exclusive.

The second regex looks closest. Here is an example:

@"^(http|https)://(\b(?:\d{1,3}\.){3}\d{1,3}\b)$"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.