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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With