c# - How to replace string's words first and last characters
问题描述
I have following table structure in my database:
+----+---------------------------------------------------------------------------------+
| ID | Message |
+----+---------------------------------------------------------------------------------+
| 1 | { "Body": "lorrem impsum test for @@xxx@@ via @@yyy@@. IsMasa lora @@zzz@@." } |
+----+---------------------------------------------------------------------------------+
This is how I get the data from the SP
SqlParameter[] parameters = new SqlParameter[1];
parameters[0] = DataAccessManager.GetParameter("@ID", DbType.Int32, id);
DataSet dataset = DataAccessManager.ExecuteStoredProcedure("spGetMessageBody", parameters);
if (dataset != null && dataset.Tables[0] != null && dataset.Tables[0].Rows.Count > 0)
{
return dataset.Tables[0].AsEnumerable().Select(row => new MessageTemplate()
{
TemplateID = row.Field<int>("ID"),
NotifyEvent = row.Field<string>("MessageBody")
}).ToList();
}
else
{
return null;
}
I need to get the Message
JSON value from the database and replace it as follows,
lorrem impsum test for [xxx] via [yyy]. IsMasa lora [zzz].
I need to get JSON Body
key value and replace @@
by [
and ]
. Above method should return this output
lorrem impsum test for [xxx] via [yyy]. IsMasa lora [zzz].
解决方案
You can use this to replace every first occurrence of @@
with [
string myText = "lorrem impsum test for @@xxx@@ via @@yyy@@. IsMasa lora @@zzz@@.";
string firstResult = Regex.Replace(myText, "((?:(?!@@).)*)@@((?:(?!@@).)*@@)", "$1[$2");
And then replace all the remaining @@
using string.Replace
string finalResult = firstResult.Replace("@@", "]");
Regex:
((?:(?!@@).)*) - first group having a non-capturing group, anything until the first occurrence of @@
@@ - first occurrence of @@
((?:(?!@@).)*@@) - second group having the second occurrence of @@
推荐阅读
- ruby-on-rails - 如何在 Puma 服务器的现有端口上初始化 Websocket?
- matlab - 补零前后图像的自相关函数
- c - 我如何使用 sscanf 获取带有 / 分隔符的 int
- smtp - 从 GitHub 重新下载后 PHPMailer 6.0.5 无法正常工作 - 语法错误
- javascript - jQuery:tablesorter 无法处理使用 jquery load() 加载的表
- unity3d - Unity 2D 反射/弹跳
- python - 在列表推导中处理 lambda 表达式中的元组
- c# - 如何在 Frames/IFrames 中获取 HtmlElement 值?
- azure - Azure 中的 Powershell 脚本
- plugins - 您可以在 Adobe XD 插件中使用 ES2015+ 功能 (ES6) 吗?