pmillio
pmillio

Reputation: 1149

Replace occurence of string with url in string

Hi i have some text which is meant to be displayed within a label.

"Hey @ronald and @tom where are we going this weekend"

What i need to do is change it to this instead

"Hey www.domain.com/ronald and www.domain.com/tom where are we going this weekend"

Now i have this code which someone off stackoverflow has helped me construct, however i am lost on what to do in the next step.

        Regex regex = new Regex(@"@[\S]+");
        MatchCollection matches = regex.Matches(strStatus);

        foreach (Match match in matches)
        {
            string Username = match.ToString().Replace("@", "");


        }

I cannot set the label in the foreach because it would disregard the last word replaced, i hope i am making sense.

Upvotes: 1

Views: 841

Answers (2)

Stavros Zotalis
Stavros Zotalis

Reputation: 726

            string strStatus = "Hey @ronald and @tom where are we going this weekend";

        Regex regex = new Regex(@"@[\S]+");
        MatchCollection matches = regex.Matches(strStatus);

        foreach (Match match in matches)
        {
            string Username = match.ToString().Replace("@", "");
            strStatus = regex.Replace(strStatus, "www.domain.com/" + Username, 1);

        }
    }

Upvotes: 1

tvanfosson
tvanfosson

Reputation: 532605

Keep the usernames you find in a list. Iterate over these from longest to shortest, replacing each occurrence of @[username] with www.domain.com/[username]. The reason to do longest to shortest is to avoid replacing partial matches, as in "Hey, @tom and @tomboy ..." This certainly isn't the most efficient way to do the replacement (since you do a full string scan for each username, but given your example I suspect your strings are short and the lack of efficiency weighs less than the simplicity of this mechanism.

var usernames = new List<string>();
Regex regex = new Regex(@"@[\S]+");
MatchCollection matches = regex.Matches(strStatus);

foreach (Match match in matches)
{
    usernames.Add( match.ToString().Replace("@", "") );
}

// do longest first to avoid partial matches
foreach (var username in usernames.OrderByDescending( n => n.Length ))
{
    strStatus = strStatus.Replace( "@" + username, "www.domain.com/" + username );
}

If you want to construct actual links it would look like:

strStatus = strStatus.Replace( "@" + username,
                               string.Format( "<a href='http://www.domain.com/{0}'>@{0}</a>", username ) );

Upvotes: 1

Related Questions