【问题标题】:Find and Replace all words starting with # and wrap the hashtagged text in HTML查找并替换所有以 # 开头的单词,并将标签文本包装在 HTML 中
【发布时间】:2019-04-02 16:33:50
【问题描述】:

如果这是重复的,我深表歉意,但我似乎找不到我的答案,我一直在寻找某个时间。使用 C# 或正则表达式,我试图在字符串中查找和替换所有带标签的单词并将它们包装在 HTML 标记中。

示例输入文本:

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

理想的输出文本

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>

我尝试了以下方法,但运气不佳

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);

任何帮助将不胜感激。

【问题讨论】:

    标签: c# regex replace find


    【解决方案1】:

    你可以使用

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

    regex demo

    #\w+ 匹配 #,然后是 1 个或多个单词字符(字母、数字、_ 等),$&amp; 引用整个匹配值(因此,无需在整个正则表达式模式)。

    【讨论】:

    • 也感谢 Wiktor 的演示。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 2023-03-31
    • 2013-11-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多