flre icon indicating copy to clipboard operation
flre copied to clipboard

named groups demo

Open jk987 opened this issue 9 years ago • 3 comments

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. (?)

jk987 avatar Mar 18 '16 16:03 jk987

You can use TFLRE.NamedGroupIndices for get the index of a named group string.

BeRo1985 avatar Mar 18 '16 16:03 BeRo1985

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?

jk987 avatar Mar 19 '16 09:03 jk987

GroupIndex := FLREInstance.NamedGroupIndices['MyGroupName'];

where -1 = group name doesn't exist

BeRo1985 avatar Mar 22 '16 03:03 BeRo1985