更新
正如 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/