1

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.

2 Answers 2

1

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 ) );
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this is what im looking for.
@pmillio - if you're not going to replace them with actual links, the partial match issue doesn't come into play and you can use @Blim's simpler method.
1
            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);

        }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.