Regex可以删除字符串中多个环绕的{quot;TextWithHtml";:和}

本文关键字:quot TextWithHtml 删除 字符串 Regex | 更新日期: 2023-09-27 18:19:45

有没有一种方法可以操作包含以下内容的字符串:

{"Correct":true,"Explanation":{"TextWithHtml":null},"ImageFile":null,"Response":false,"Text":{"TextWithHtml":"1 -1 4 -16"}},{"Correct":true,"Explanation":{"TextWithHtml":null},"ImageFile":null,"Response":false,"Text":{"TextWithHtml":"1 -1 4 2147483644"}}]

去掉CCD_ 1和CCD_?

Regex可以删除字符串中多个环绕的{quot;TextWithHtml";:和}

IMHO,您应该创建一个类

public class YourClassName
{
    public string TextWithHtml{ get; set; }
}

并修改您的答案类别

public class Answer : AuditableTable
{
    public bool Correct { get; set; }
    public bool Response { get; set; }
    public YourClassName Text { get; set; }
    public string ImageFile { get; set; }
    public YourClassName Explanation { get; set; }
}

试试这个:

string sSource = @"{"Correct":true,"Explanation":{"TextWithHtml":null},"ImageFile":null,"Response":false,"Text":{"TextWithHtml":"1
    -1 4 -16"}},{"Correct":true,"Explanation":{"TextWithHtml":null},"ImageFile":null,"Response":false,"Text":{"TextWithHtml":"1
    -1 4 2147483644"}}]"; 
string pattern = @"({"TextWithHtml":)|(?(?<=({"TextWithHtml":)[^}]*)})"; 
string sResult= Regex.Replace(@sSource, @pattern, "");

一些解释:

删除

{"TextWithHtml":

或删除

}

如果前面是:

{"TextWithHtml":加上一些不是"{"的字符

编辑:

对于TextWithHtml字符串中的{}个方括号:

({"TextWithHtml":)|(?(?<=((({"TextWithHml":)(("[^"]*")|null))})

不过,转义引号字符(''")仍然存在问题。

要匹配所需的所有数据,请使用以下正则表达式:

{"TextWithHtml":.*?}

使用Regex.Replace(…)将匹配项替换为子字符串。

string data = match.Value.Substring(16, match.Value.Length-16-1);

接下来,如果数据包含"标记:

data.Trim('"');