【问题标题】:Regex performance issue on a really big string非常大的字符串上的正则表达式性能问题
【发布时间】:2016-01-15 22:22:52
【问题描述】:

现在我是使用正则表达式的新手,非常感谢您的帮助。

我有一个非常大的字符串(我正在将 as3 文件解析为 json),我需要在对象中找到那些尾随逗号。

这是我正在使用的正则表达式

public static string TrimTraillingCommas(string jsonCode)
{
    var regex = new Regex(@"(.*?),\s*(\}|\])", (RegexOptions.Multiline));

    return regex.Replace(jsonCode, m => String.Format("{0} {1}", m.Groups[1].Value, m.Groups[2].Value));
}

它的问题是它真的很慢。如果不在字符串中使用它,完成程序的时间是:00:00:00.0289668 和它:00:00:00.4096293

有人可以建议一种改进的正则表达式或算法来更快地替换那些尾随逗号。

Here is where i start from ( the string with the trailing commas )

Here is the end string I need

【问题讨论】:

  • 编译它会得到什么?与:RegexOptions.Compiled | RegexOptions.Multiline
  • 不是每次调用TrimTraillingCommas 时都声明一个新的Regex,您可以将其声明为静态。否则,每次运行时都需要“编译”正则表达式。不管正则表达式有多复杂
  • 等等,为什么一开始有逗号?如果这是valid json,应该没有吧?如果您有有效的 json,也许您可​​以完全消除对 RegEx 的需求。
  • @null 关键是我没有有效的 json。我什至没有 json .. 我有一堆 as3 文件,其中有很多错误,我需要将它们的值解析为有效的 json 文件。
  • @JordanKanchelov “错误”是什么意思,它们会编译吗?

标签: c# .net regex


【解决方案1】:

您可以通过消除捕获组来简化正则表达式,将后者的目的替换为前瞻:

var regex = new Regex(@",\s*(?=\}|\])");
return regex.Replace(jsonCode, " ");

【讨论】:

  • 这正是我所需要的:)。谢谢
【解决方案2】:

你不需要第一个表达式.*?,你可以转换交替
进入一个字符类。这是你能做的最好的事情。

var regex = new Regex(@",[^\S\r\n]*([}\]])");
return regex.Replace(jsonCode, " $1");

【讨论】:

    猜你喜欢
    • 2013-11-19
    • 2010-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-10
    相关资源
    最近更新 更多