C# code to linkify urls in a string

后端 未结 7 1404
Happy的楠姐
Happy的楠姐 2020-11-28 06:17

Does anyone have any good c# code (and regular expressions) that will parse a string and \"linkify\" any urls that may be in the string?

7条回答
  •  南笙
    南笙 (楼主)
    2020-11-28 06:47

    protected string Linkify( string SearchText ) {
        // this will find links like:
        // http://www.mysite.com
        // as well as any links with other characters directly in front of it like:
        // href="http://www.mysite.com"
        // you can then use your own logic to determine which links to linkify
        Regex regx = new Regex( @"\b(((\S+)?)(@|mailto\:|(news|(ht|f)tp(s?))\://)\S+)\b", RegexOptions.IgnoreCase );
        SearchText = SearchText.Replace( " ", " " );
        MatchCollection matches = regx.Matches( SearchText );
    
        foreach ( Match match in matches ) {
            if ( match.Value.StartsWith( "http" ) ) { // if it starts with anything else then dont linkify -- may already be linked!
                SearchText = SearchText.Replace( match.Value, "" + match.Value + "" );
            }
        }
    
        return SearchText;
    }
    

提交回复
热议问题