首页 > 解决方案 > 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].

标签: c#replacedatatable

解决方案


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 @@


推荐阅读