HTML 字符串作为使用 C# 的 JSON 输出。
我想用 ' 替换 HTML 包装器 < 和 > 之间的 "的每个实例,同时转换为 JSON。同时如果它有带有 "引号的文本,那么它不应该被替换为 ' 引号。例如。 “自 1500 年代以来”
代码 - 将所有 "替换为 ' 引号
public string Content
{
get
{
return _content;
}
set
{
if (value != null)
{
this._content = this._content.Replace("\"", "'");
}
}
}
我正在从我的 View 中获取这种形式的字符串。
E.g. model.Content = "<p> Lorem Ipsum is simply dummy text of the printing <span id= "#" ids= "#" display= "inline" ></ span > and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever "since the 1500s".<br></p>";
我正在使用 JsonConvert.SerializeObject
string output = JsonConvert.SerializeObject(model, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new CamelCasePropertyNamesContractResolver() });
预期字符串 - HTML 标记中的所有双引号都应转换为单引号,但文本引号应与使用 C# 时一样
"content": "<p><b>Lorem Ipsum</b> is simply dummy <i>text </i>of the printing <span id='#' ids='#' display='inline'></span> and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever \"since the 1500s\".</p>",
最佳答案
我想你想用 '. 替换 < 和 > 之间的每个 "实例。
因此,您在字符串中查找每个 ",在后面查找 <,在前面查找 >。正则表达式如下所示:
(?<=\<[^<>]*)"(?=[^><]*\>)
所以你可以使用
outputString = Regex.Replace(inputString, "(?<=\\<[^<>]*)\"(?=[^><]*\\>)", "'");
然后你想在你的字符串中转义其他 "。为此你可以使用
outputString = outputString.Replace(@"""", @"\""");
或
outputString = outputString.Replace("\"", "\\\"");
我创建了一个控制台应用程序来测试它,
Console.WriteLine("Enter The String : ");
string input = Console.ReadLine();
string pattern = "(?<=\\<[^<>]*)\"(?=[^><]*\\>)";
string output = Regex.Replace(input, pattern, "'");
output = output.Replace(@"""", @"\""");
Console.WriteLine(output);
Console.ReadKey();
输入字符串是你提供的字符串,然后输出将是,
<p> Lorem Ipsum is simply dummy text of the printing <span id= '#' ids= '#' display= 'inline' ></ span > and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever \"since the 1500s\".<br></p>
关于c# - 使用 C# 将 HTML 字符串作为 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48002499/