【发布时间】:2020-01-03 23:36:34
【问题描述】:
我有一个包含 JSON 字符串的文件。长串。大约 70 万个符号。
我正在尝试反序列化它。
但它包含 \r 和 \n 等符号,应替换为逗号 ,。
我尝试使用Regex 进行操作,但它卡在上面没有错误。
private static readonly Regex Pattern = new Regex("(\r\n|\r|\n)", RegexOptions.Compiled | RegexOptions.IgnoreCase);
Pattern.Replace(dataString, ",");
还尝试将string 转换为StringBuilder 并使用简单的.Replace
private readonly IDictionary<string, string> replacements = new Dictionary<string, string> { { "\r\n", "," }, { "\r", "," }, { "\n", "," } };
foreach (var replacement in this.replacements)
{
dataStringBuilder.Replace(replacement.Key, replacement.Value);
}
第二种情况更好,但直到文件变大为止。 所以现在我在这两种情况下都被卡住了。
还有其他推荐的更快的解决方案吗?
【问题讨论】:
-
替换不会改变您的输入,它会返回一个新值。您永远无法更改现有字符串,只需创建一个新字符串
-
@HansKesting,哦,是的......刚刚注意到这一点。谢谢。将尝试此修复
标签: c# .net regex string replace