如何替换字符串的单词的第一个和最后一个字符

时间:2019-10-16 06:24:30

标签: c# replace datatable

我的数据库中具有以下表结构:

+----+---------------------------------------------------------------------------------+
| ID |                                     Message                                     |
+----+---------------------------------------------------------------------------------+
|  1 |  { "Body": "lorrem impsum test for @@xxx@@ via @@yyy@@. IsMasa lora @@zzz@@." } |
+----+---------------------------------------------------------------------------------+

这就是我从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;
}

我需要从数据库中获取Message JSON值,并按如下所示替换它,

lorrem impsum test for [xxx] via [yyy]. IsMasa lora [zzz].

我需要获取JSON Body密钥值,并将@@替换为[]。上面的方法应该返回此输出

lorrem impsum test for [xxx] via [yyy]. IsMasa lora [zzz].

1 个答案:

答案 0 :(得分:1)

您可以使用此方法将@@的每个首次出现的[替换为string myText = "lorrem impsum test for @@xxx@@ via @@yyy@@. IsMasa lora @@zzz@@."; string firstResult = Regex.Replace(myText, "((?:(?!@@).)*)@@((?:(?!@@).)*@@)", "$1[$2");

@@

然后使用string.Replace替换所有剩余的string finalResult = firstResult.Replace("@@", "]");

((?:(?!@@).)*)  - first group having a non-capturing group, anything until the first occurrence of @@ 
@@               - first occurrence of @@
((?:(?!@@).)*@@) - second group having the second occurrence of @@

正则表达式:

$credentials = request(['email', 'password']); $user=Auth::attempt($credentials);