Regex string issue in making plain text urls clickable

前端 未结 4 881
死守一世寂寞
死守一世寂寞 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:17

    Try this

    Regex regx = new Regex("(?))(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
    

    It should work for your example.

    (?)) is a negative lookbehind, that means the pattern matches only if it is not preceeded by "href='" or ">".

    See lookarounds on regular-expressions.info

    and the especially the zero-width negative lookbehind assertion on msdn

    See something similar on Regexr. I had to remove the alternation from the look behind, but .net should be able to handle it.

    Update

    To ensure that there are also (maybe possible) cases like "

    ftp://www.def.com

    " correctly handled, I improved the regex

    Regex regx = new Regex("(?]*>))(http|https|ftp|ftps)://([\\w+?\\.\\w+])+([a-zA-Z0-9\\~\\!\\@\\#\\$\\%\\^\\&\\*\\(\\)_\\-\\=\\+\\\\\\/\\?\\.\\:\\;\\'\\,]*)?", RegexOptions.IgnoreCase);
    

    The lookbehind (?]*>)) is now checking that there is not a "href='" nor a tag starting with "

    The output of the teststring

    ttt ftp://www.abc.com abc 

    ftp://www.def.com

    abbbbb http://www.ghi.com

    is with this expression

    ttt ftp://www.abc.com abc 

    ftp://www.def.com

    abbbbb http://www.ghi.com

提交回复
热议问题