Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
590 views
in Technique[技术] by (71.8m points)

asp.net - Recognize URL in plain text

This should be easy, but I'm not sure how to best go about it. I have a WinForms app that lets the user type in long descriptions. Occaisionally, they would type in URLs, and the RichTextBox would recognize them and make them clickable when displayed.

I'm moving the app to the web, and I'm not sure how to make those same URLs clickable. Is there some semi-automatic way to convert "http://www.google.com" or "www.google.com" to clickable links? Do I have to resort to RegEx matching?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's actually a very difficult problem. You can get close, but not perfect, with regular expressions. There's a very nice breakdown of potential regex patterns to consider here: http://www.regexguru.com/2008/11/detecting-urls-in-a-block-of-text/

The last one he lists seems like it's probably good enough for most purposes:

(?:(?:https?|ftp|file)://|www.|ftp.)
  (?:([-A-Z0-9+&@#/%=~_|$?!:,.]*)|[-A-Z0-9+&@#/%=~_|$?!:,.])*
  (?:([-A-Z0-9+&@#/%=~_|$?!:,.]*)|[A-Z0-9+&@#/%=~_|$])

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...