Regex string issue in making plain text urls clickable

前端 未结 4 859
死守一世寂寞
死守一世寂寞 2021-01-05 15:48

I need a working Regex code in C# that detects plain text urls (http/https/ftp/ftps) in a string and make them clickable by putting an anchor tag around it with same url. I

4条回答
  •  鱼传尺愫
    2021-01-05 16:16

    I know I arrived late to this party, but there are several problems with the regex that the existing answers don't address. First and most annoying, there's that forest of backslashes. If you use C#'s verbatim strings, you don't have to do all that double escaping. And anyway, most of the backslashes weren't needed in the first place.

    Second, there's this bit: ([\\w+?\\.\\w+])+. The square brackets form a character class, and everything inside them is treated either as a literal character or a class shorthand like \w. But getting rid of the square brackets isn't enough to make it work. I suspect this is what you were trying for: \w+(?:\.\w+)+.

    Third, the quantifiers at the end of the regex - ]*)? - are mismatched. * can match zero or more characters, so there's no point making the enclosing group optional. Also, that kind of arrangement can result in severe performance degradation. See this page for details.

    There are other, minor problems, but I won't go into them right now. Here's the new and improved regex:

    @"(?n)(https?|ftps?)://\w+(\.\w+)+([-a-zA-Z0-9~!@#$%^&*()_=+/?.:;',\\]*)(?![^<>]*+(>|))"
    

    The negative lookahead - (?![^<>]*+(>|)) is what prevents matches inside tags or in the content of an anchor element. It's still very crude, though. There are several areas, like inside

提交回复
热议问题