c# - 如果找到特定的子字符串,我想在字符串中添加一些 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.";
你能帮我找到更好的选择吗?
我会很感激你的帮助。先感谢您。
解决方案
您可以尝试使用以下代码:
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>.
推荐阅读
- javascript - Cordova - 单击提交按钮时的 ExecuteScript 回调
- mocha.js - WebdriverIo 对于异步测试和钩子,确保调用“done()”;如果返回一个 Promise,确保它解决
- pyspark - 如何从pyspark中的数据框中选择所有结构?
- shell - 如何删除所有超过 3 个斜杠的行?
- elasticsearch - 从日志消息中获取 JSON 子字符串
- azure - 我无法删除天蓝色警报
- java - 服务器端 Omnifaces 推送。PushContext 为空
- kotlin - 如何在 Kotlin 的 .forEach 迭代中获取 Set 中的特定元素
- python - 如何将 pandas 数据框写入现有的启用宏的 Excel 电子表格 (.xlsm)
- python - 参数化泛型不能与类或实例检查一起使用