首页 > 解决方案 > 如果找到特定的子字符串,我想在字符串中添加一些 html 标记

问题描述

我需要的是当用户添加带有主题标签的消息时,同时显示消息主题标签应该看起来不同。

在.Net中,我有一个像

var stringVal = "Hello, #goodmorning, this is sample #cool text.";

我需要将标签值包装在标签中并获取新字符串

var resultString = "Hello <span style="color:blue;">#goodmorning</span>, this is sample <span style="color:blue;">#cool</span> text.";

你能帮我找到更好的选择吗?

我会很感激你的帮助。先感谢您。

标签: c#asp.net.netasp.net-core.net-standard

解决方案


您可以尝试使用以下代码:

string str = "Hello #goodmoring! This is #nice.";
    
List<string> aLst = new List<string>(); 
    
foreach (Match match in Regex.Matches(s, @"(?<!\w)#\w+")) //Using regex to check if any word starts with #
{
    aLst.Add(match.Value); //Adding to a list if found
}
    
foreach (var replacement in aLst)
{
    str = str.Replace(replacement, "<span style='color:blue;'>" + replacement + "</span>"); //Finally replacing the value starts with #
}
    
Console.WriteLine(str);

预期输出

Hello <span style='color:blue;'>#goodmoring</span>! This is <span style='color:blue;'>#nice</span>.

推荐阅读