Fat Monk
Fat Monk

Reputation: 2265

freepascal regexp replace

Is there an easy way to do a RegExp replace in FreePascal/Lazarus?

Hunting around I can see that I can do a match fairly easily, but I'm struggling to find functions to do a search and replace.

What I'm trying to acheive is as follows.

So essentially I have:

<?Line1?>
Line2
Line3

And I want to do a RegExp type search and replace for '<?Line1?>' replaceing with '<?Line1?>\n<![DTD\nINFO WOULD\nGO HERE\n!]' to give me:

<?Line1?>
<![DTD
INFO WOULD
GO HERE
!]
Line2
Line3

For example in PHP I would use:

preg_replace('/(<\?.*\?>)/im','$1
<![DTD
INFO WOULD
GO HERE
!]',$sourcestring);

But there doesn't seem to be an equivalent set of regexp functions for FreePascal / Lazarus - just a simple/basic RegExp match function.

Or is there an easier way without using regular expressions - I don't want to assume that the declaration is always there in the correct position on Line 1 though - just to complicate things.

Thanks,

FM

Upvotes: 3

Views: 3634

Answers (1)

Roland Chastain
Roland Chastain

Reputation: 61

As far as I know, the PerlRegEx unit isn't compatible with Free Pascal. But you can use the RegExpr unit, which comes with Free Pascal.

If I understand correctly, you want a replacement with substitution. Here is a simple example that you can adapt to your need.

{$APPTYPE CONSOLE}
{$IFDEF FPC}{$MODE DELPHI}{$ENDIF}

uses
  regexpr;

var
  s: string;

begin
  s := 'My name is Bond.';

  s := ReplaceRegExpr(
    'My name is (\w+?)\.',
    s,
    'His name is $1.',
    TRUE // Use substitution
  );

  WriteLn(s); // His name is Bond.
  ReadLn;
end.

Upvotes: 2

Related Questions