0

whats is the best way to find and replace url in string. Now I use regexp

Regex regx = new Regex("http(s)?://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*([a-zA-Z0-9\\?\\#\\=\\/]){1})?",
RegexOptions.IgnoreCase);
string output = regx.Replace(text, "<a href=\"$0\" target=\"_blank\">$0</a> ");

but this is ugly code and works badly, becouse it is not find www.server.com and http://server.nonexist is bad url bur regexp find this.

What is the best way to do fuction which get some long string and return string with html link?

for example

input = Lorem ipsum dolor sit http://www.server.com/ amet
output = Lorem ipsum dolor sit <a href="http://www.server.com/"> http://www.server.com/</a> amet
StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
Lenny
  • 155
  • 3
  • 11
  • 1
    I would not say that. This is a completely different topic – Lenny May 06 '14 at 17:22
  • 1
    I don't see how this is a duplicate of the question. – zmbq May 06 '14 at 17:22
  • @ErikPhilips This isn't a duplicate, as the regex is to match a URL and be replaced with the tag, not the other way around. – ssube May 06 '14 at 17:25
  • [Obligatory link](http://stackoverflow.com/q/4231382/471272) to a real answer, not a dumb joke that doesn’t even apply here. – tchrist Jun 08 '14 at 20:05

1 Answers1

1

You want to make sure the URL is of a legal website, or at least an existing server? A regular expression can't do that.

You'll need to do this in two steps - first is your RegEx, only update it to include www.something.or.other.com, too, even though there's no protocol. Make sure you put the domain name in a group, so that after there's a match, accessing it is going to be easy.

Scan your string for the regular expression. Then go over the matches and perform the second step - check that the domain is legal. If it is, wrap it with an <a href..., if not - leave it as it is, or warn the user, or something.

zmbq
  • 38,013
  • 14
  • 101
  • 171