Regular Expressions in Pascal

Our program demonstrates common regular expression tasks in Pascal. Here’s the full source code:

program RegularExpressions;

uses
  RegExpr, SysUtils;

var
  r: TRegExpr;
  match: Boolean;
  s: string;
  i, j: Integer;
  matches: TStringList;

begin
  // This tests whether a pattern matches a string.
  match := ExecRegExpr('p([a-z]+)ch', 'peach');
  WriteLn(match);

  // For other regexp tasks, we'll create a TRegExpr object.
  r := TRegExpr.Create('p([a-z]+)ch');

  // Many methods are available on this object. Here's a match test like we saw earlier.
  WriteLn(r.Exec('peach'));

  // This finds the match for the regexp.
  if r.Exec('peach punch') then
    WriteLn(r.Match[0]);

  // This also finds the first match but returns the start and end indexes for the match.
  if r.Exec('peach punch') then
    WriteLn('idx: ', r.MatchPos[0], ' ', r.MatchLen[0]);

  // The Subexpression variants include information about both the whole-pattern matches 
  // and the submatches within those matches.
  if r.Exec('peach punch') then
  begin
    WriteLn(r.Match[0], ' ', r.Match[1]);
  end;

  // To find all matches for a regexp, we can use a loop.
  matches := TStringList.Create;
  try
    s := 'peach punch pinch';
    i := 1;
    while r.Exec(s, i) do
    begin
      matches.Add(r.Match[0]);
      i := r.MatchPos[0] + r.MatchLen[0];
    end;
    WriteLn(matches.CommaText);
  finally
    matches.Free;
  end;

  // The regexp package can also be used to replace subsets of strings with other values.
  WriteLn(r.Replace('a peach', '<fruit>', True));

  // We can also use a function to transform matched text.
  s := r.Replace('a peach', 
    function(const AMatch: string): string
    begin
      Result := UpperCase(AMatch);
    end, 
    True);
  WriteLn(s);

  r.Free;
end.

To run the program, save it as regular_expressions.pas and compile it with a Pascal compiler like Free Pascal:

$ fpc regular_expressions.pas
$ ./regular_expressions

This will output the results of various regular expression operations.

Note that Pascal doesn’t have a built-in regular expression library like Go does. We’re using the TRegExpr library, which is a popular choice for regular expressions in Pascal. The syntax and available methods might differ slightly from Go’s regexp package, but the core concepts remain the same.

For a complete reference on TRegExpr, check the official documentation of the library you’re using.