regex - Delphi 正则表达式的最大模式 "separation"?

标签 regex delphi

更新

正如 Graymatter 所观察到的,当第二个目标之前至少有 2 个额外换行符时,正则表达式将无法匹配。也就是说,将串联循环更改为“for I := 0 to 1”将使正则表达式匹配失败。

<小时/>

如下面的代码所示,在没有连接的情况下,程序可以使用正则表达式获取两个值。但是,通过串联,程序无法获取这两个值。

您能帮忙评论一下原因和解决方法吗?

program Project1;

{$APPTYPE CONSOLE}

uses
  // www.regular-expressions.info/delphi.html
  // http://www.regular-expressions.info/download/TPerlRegEx.zip
  PerlRegEx,
  SysUtils;

procedure Test;
var
  Content: UTF8String;
  Regex: TPerlRegEx;
  GroupIndex: Integer;
  I: Integer;
begin
  Regex := TPerlRegEx.Create;
  Regex.Regex := 'Value1 =\s*(?P<Value1>\d+)\s*.*\s*Value2 =\s*(?P<Value2>\d*\.\d*)';

  Content := '';
  for I := 0 to 10000000 do
  begin
    // Uncomment here to see effect
    // Content := Content + 'junkjunkjunkjunkjunk' + sLineBreak;
  end;

  Regex.Subject := 'junkjunkjunkjunkjunk' +
    sLineBreak + ' Value1 = 1' +
    sLineBreak + 'junkjunkjunkjunkjunk' + Content +
    sLineBreak + ' Value2 = 1.23456789' +
    sLineBreak + 'junkjunkjunkjunkjunk';

  if Regex.Match then
  begin
    GroupIndex := Regex.NamedGroup('Value1');
    Writeln(Regex.Groups[GroupIndex]);
    GroupIndex := Regex.NamedGroup('Value2');
    Writeln(Regex.Groups[GroupIndex]);
  end
  else
  begin
    Writeln('No match');
  end;
  Regex.Free;
end;

begin
  Test;
  Readln;
end.

最佳答案

添加此行有效。

  Regex.Options := [preSingleLine];

来自documentation :

preSingleLine

Normally, dot (.) matches anything but a newline (\n). With preSingleLine, dot (.) will match anything, including newlines. This allows a multiline string to be regarded as a single entity. Equivalent to Perl's /s modifier. Note that preMultiLine and preSingleLine can be used together.

当第二个目标之前只有一个换行符时,即使没有 preSingleline,正则表达式也可以匹配。原因是因为\s 可以匹配行返回。

关于regex - Delphi 正则表达式的最大模式 "separation"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23891153/

相关文章:

delphi - 没有表单的非视觉组件

image - 在 Firemonkey 中拍摄和保存照片

regex - 正则表达式重构

c# - 匹配目录模式的正则表达式

使用 RegExp 的 Javascript 正则表达式匹配

c - 删除 C 中的部分字符串(正则表达式?)

Java 正则表达式将字符串和字符与 ' "匹配 '

unit-testing - 使用 Bold for Delphi 框架进行编码时提高可测试性

delphi - Delphi 2009 需要 DataMatrix ECC 200 (ISO/IEC 16022) 条码组件

delphi - 在这种特殊情况下,XML 文件或数据库(文件经常更新)