Ago
Ago

Reputation: 765

Other Ways to Check if String is a Regular Expression

I have this function to check if a string is a regular expression and it works fine :

function IsValidRegEx(aString: string): Boolean;
var
  aReg : TRegEx;
begin
  Result := False;
  if Trim(aString) = '' then
  begin
    Exit;
  end;

  try
    aReg := TRegEx.Create(aString);
    if aReg.IsMatch('asdf') then
    begin
    end;
    Result := True;
  except
  end;
end;

the problem is it always raise a debugger exception notification if string value is false. I want to eliminate that notification. There is an option to ignore that exception in the notification itself but I don't want it. As much as possible it would be the codes that will adjust.

Upvotes: 1

Views: 178

Answers (1)

David Heffernan
David Heffernan

Reputation: 612964

If you want to use this approach, then you can't avoid exceptions being raised by the Delphi regex library. You'd need to dig down to the PCRE library that Delphi uses to implement its regex library. For instance:

{$APPTYPE CONSOLE}

uses
  System.RegularExpressionsAPI;

function IsValidRegEx(const Value: UTF8String): Boolean;
var
  CharTable: Pointer;
  Options: Integer;
  Pattern: Pointer;
  Error: PAnsiChar;
  ErrorOffset: Integer;
begin
  CharTable := pcre_maketables;
  Options := PCRE_UTF8 or PCRE_NEWLINE_ANY;
  Pattern := pcre_compile(PAnsiChar(Value), Options, @Error, @ErrorOffset, CharTable);
  Result := Assigned(Pattern);
  pcre_dispose(Pattern, nil, CharTable);
end;

begin
  Writeln(IsValidRegEx('*'));
  Writeln(IsValidRegEx('.*'));
  Readln;
end.

Note that I have written this with Delphi XE7, as I don't have access to XE2. If this code doesn't compile, then it should not be too hard to study the source code for the Delphi regex library to work out how to achieve the same in XE2.

Upvotes: 4

Related Questions