flre
flre copied to clipboard
named groups demo
Hi,
is there some demo of getting named groups?
I notice that in NamedGroups[] is name followed by group number which I can use as index into captures[].
Here is how I did it in my class. But it is ugly as hell:
var variables: array of record Key, Value: String;
...
flre := TFLRE.Create(Self.RegExp,[]);
try
try
if flre.Match(Self.LastPacket, captures, 1) then begin
//for s in flre.NamedGroups do Log('NamedGroup: '+s);
//for i := 0 to Length(captures)-1 do Log('i: %d, start: %d, len: %d', [i, captures[i].Start, captures[i].Length]);
SetLength(variables, 0);
i := 1; /// Skip first named group because it is 'wholematch'.
while i < flre.NamedGroups.Count-1 do begin
if StrToIntDef(flre.NamedGroups[i], -1)=-1 then begin /// Name is not a number.
captureIndex := StrToIntDef(flre.NamedGroups[i+1], -1); /// Next group name is a number.
if (captureIndex >= 0) and (captureIndex < Length(captures)) then begin
SetLength(variables, Length(variables)+1);
with variables[Length(variables)-1] do begin
Key := flre.NamedGroups[i];
Value := Copy(Self.LastPacket, captures[captureIndex].Start, captures[captureIndex].Length);
Log('Key: %s, Value: %s', [Key, Value]);
end;
Inc(i);
end;
end;
Inc(i);
end;
end;
except
on E: Exception do Log(E);
end;
finally
flre.Free();
end;
But I hope there is a better way to get (Key, Value) pairs. (?)
You can use TFLRE.NamedGroupIndices for get the index of a named group string.
I noticed that this property exists. But maybe I'm too stupid but I didn't recognize how to use it. Do you please have some example or documentation for this?
GroupIndex := FLREInstance.NamedGroupIndices['MyGroupName'];
where -1 = group name doesn't exist