-1

Currently I have my program able to achieve this with IP address using regex.Replace() to search the input string for an IP and swap it with the new one keeping the start and end of the URL

so with the following test1 goes from "https://11.1.11.11:8080/" > "https://22.2.22.22:8080/"

Regex ipAddress = new Regex("\\b(?:(?: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]?)\\b", RegexOptions.Compiled);
string test1 = "https://11.1.11.11:8080/";
Console.WriteLine(ipAddress.Replace(test1,"22.2.22.22"));

however when I try this with a host name for example "https://google.com:8080/" > "https://facebook.com:8080/" the following code doesn't find the hostname? How come with the IP adresss it is able to find and replace the IP but with hostname it cannot?

Regex hostname = new Regex(@"^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9]*)\.)*([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9]*)$");
string test2 = "https://google.com:8080/";
Console.WriteLine(hostname.Replace(test1, "facebook.com"));
C. Dodds
  • 325
  • 3
  • 12

1 Answers1

0

Your second hostname regex is incorrect. It's looking for any number of sets of three repeating characters (a-z, A-Z or 0-9) followed by a period, any number of times at the beginning of the string. It's then looking for any number of characters (same set) and then the end of the string.

I'm afraid I can't suggest a regex as I don't know your requirements, perhaps look at the RegExLib site (http://www.regexlib.com/Search.aspx)? They have many user submitted regex patterns for common situations. They've also got an online regex tester to help you (although there's a better one at http://regexstorm.net/tester).

If you can give more information about what you're trying to replace and what the likely input will be (i.e. will the protocol always be there (http/https/ftp etc.)?) someone will be able to help a little more with the pattern you require.

Loki
  • 188
  • 1
  • 11