Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find and Replace all words starting with # and wrap the hashtagged text in HTML

I apologize if this is a duplicate, but I can't seem to find my answer and I have been looking for sometime now. Using C# or a regular expression, I'm trying to find and replace all hashtagged words within a string and wrap them in HTML tags.

Example Input Text:

I would like to wrap #AllHashtags with html #Code to make it #StandOut

Ideal Output Text

I would like to wrap <span class="yellow">#AllHashtags</span> with html <span class="yellow">#Code</span> to make it <span class="yellow">#StandOut</span>

I've tried the following, but not luck

tweet.Text = "<span class='yellow'>" + tweet.Hashtags + "</span>";

tweet.Text.Replace("#", "<span class='yellow'>#");

tweet test = tweet.Text.IndexOf("#", 0);

var containsHastag = tweet.Text.Contains("#", StringComparer.OrdinalIgnoreCase);

Any help would be appreciated.

like image 543
GRU119 Avatar asked Sep 05 '25 03:09

GRU119


1 Answers

You may use

var res = Regex.Replace(s, @"#\w+", "<span class=\"yellow\">$&</span>");

See the regex demo

The #\w+ matches # and then 1 or more word chars (letters, digits, _, etc.) and $& references the whole match value (hence, no need using a capturing group around the whole regex pattern).

enter image description here

like image 109
Wiktor Stribiżew Avatar answered Sep 07 '25 20:09

Wiktor Stribiżew