【问题标题】:Using Regex in Delphi Xe with rawbytestring在 Delphi Xe 中使用带有 rawbytestring 的正则表达式
【发布时间】:2013-10-10 03:10:14
【问题描述】:

在我的项目中,我需要使用正则表达式在 400mb 的 TMemoryStream 对象中查找一些数据。我正在检查 delphi xe3 中的新正则表达式,但函数仅与接收到的字符串参数匹配,而不是原始字节字符串或指针。 我用这种方式定义了模式ok:

MyPatt:="\x8A\x8A(..)\x8A"

问题是如何在二进制rawdata里面找到 我试过了

TRegex.Match((MyStreamObject.Memory)^,MyPatt);

但没有成功。 我尝试了这个,但也没有成功

TRegex.Match(String((MyStreamObject.Memory)^),MyPatt);

问题是如果以 0x00 开头的 rawbinary 对象被截断。

如何使用指针或 rawbinarystring 匹配正则表达式?

【问题讨论】:

  • 我建议在您的问题“任何想法或任何可以帮助我的现有库??”中省略最后一行。因为您已经在前一句中提出了您的问题,并且“现有库”是题外话。抱歉,我对这个主题不够熟悉,无法提供答案。
  • @JerryDodge,感谢您的旅行,主帖已编辑。
  • 您应该使用RegularExpressionsCore 单位,因为它使用UTF8。引用help:"If you're dealing with UTF-8 data, use the RegularExpressionsCore unit to avoid needless UTF-8 to UTF-16 to UTF-8 conversions."。
  • @LURD AFAIR TPerlRegEx 在RegularExpressionsCore.pas 中定义的速度非常慢。它硬编码选项PCRE_UTF8 or PCRE_NEWLINE_ANY,它们是very very very slow。

标签: regex delphi delphi-xe3


【解决方案1】:

您可以直接使用 RegEx 库 API 而不是基于字符串的 Delphi 类,后者有一些 identified (and not fixed) performance issues。

例如(兼容 Delphi 6 到 XE5):

uses
{$ifdef ISDELPHIXE}
  // use direct PCRE library as available since Delphi XE
  RegularExpressionsAPI,
{$else}
  // download from http://www.regular-expressions.info/download/TPerlRegEx.zip
  PCRE,
{$endif}
  SysUtils,
  ...

var
  compiled: PPCRE;
  extra: PPCREExtra;
  errMsg: PAnsiChar;
  errPos: integer;

  // here regexp points to your null-terminated regular expression
  compiled := pcre_compile(PAnsiChar(regexp),0,@errMsg,@errPos,nil);
  if reg=nil then begin
    CompileError;
    exit;
  end;
  extra := pcre_study(compiled,0,@errMsg);

  // now use the compiled pcre expression (once compiled, it is better to re-use compiled/extra values)
  found := pcre_exec(compiled,extra,pointer(text),StrLen(text),0,PCRE_NO_UTF8_CHECK,nil,0)>=0;

  // do not forget to release the compiled pcre expression
  pcre_dispose(compiled,extra,nil);

此代码将比TRegEx(以及从string 到UTF-8 的转换)和RegularExpressionsCore.pas 中定义的TPerlRegEx 快得多(它没有设置PCRE_NO_UTF8_CHECK,所以非常慢)。

您可以找到上述示例in our REGEXP operator for SQLite3 unit的原始代码。

【讨论】:

  • @ArnaudBouchez 你能帮忙展示一下(1)如何“重用已编译”(2)直接使用 RegEx 库 API 时如何使用“命名组”功能?
  • (1) 再次调用 pcre_exec() 使用相同的编译,额外参数,在另一个文本上 (2) 我没有代码来显示这个功能,因为我不使用它,对不起。
  • @DavidHeffernan OP 写了大约 400 MB 的文本。在这里,性能可能绝对是一个问题。我并不痴迷于性能(它是万恶之源),但如果我可以在不增加额外成本的情况下更快地完成某件事,我就会去做。
  • 使 RTL 包装器变慢的不仅是 UTF-8 转换,更重要的是 PCRE 执行选项是硬编码,并且未设置 PCRE_NO_UTF8_CHECK -请查看我的链接和the fix proposed by Andreas - which I implmented in my answer。还是not fixed。我怀疑性能对 EMB 来说并不重要——他们可能会写与你相同的评论:性能根本不相关。在 400 MB 文件上:速度提高 1000 倍是相关的。 :)
  • @DavidJesus 我没有深入了解 PCRE 是否支持空字符。我想 \x0 或 \000 会起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-08-28
  • 1970-01-01
  • 1970-01-01
  • 2017-05-04
相关资源
最近更新 更多