Home > other >  Delphi regex replace inconsistent behavior
Delphi regex replace inconsistent behavior

Time:10-20

I have below code.

  var
  result := 'DECLARE'''   #13#10   'DECLARE''''';
  result := TRegEx.Replace(result, '\A\s*DECLARE''\s*', 'abc', [roIgnoreCase]);
  ShowMessage(result);

When I run it, I got:

enter image description here

This result is expected. However, when I change the replacement string to an empty string, like this:

  result := 'DECLARE'''   #13#10   'DECLARE''''';
  result := TRegEx.Replace(result, '\A\s*DECLARE''\s*', '', [roIgnoreCase]);

  ShowMessage(result);

I got this result when run the program:

enter image description here

Why this happens? I only want to replace the first match, and that's why I use \A to anchor the regex at the beginning of the string.

CodePudding user response:

The reason why you get the results you get is because TRegEx.Replace replaces all matches in an Input string with a Replacement string.

If you want to replace only the first match then you need to use overloaded version of TRegEx.Replace that allows you to also pass the Count parameter with which you can control of how many occurrences gets replaced.

Since this overloaded version of TRegEx.Replace is declared as regular function belonging to TRegEx record and not as class function you will first have to declare variable of TRegEx record and set Pattern and Options using TRegEx.Create and then call appropriate overloaded version of Replace.

So your code should look like this:

var RegEx: TRegEx;

result := 'DECLARE'''   #13#10   'DECLARE''''';
RegEx := TRegEx.Create('\A\s*DECLARE''\s*', [roIgnoreCase]);
Result := RegEx.Replace(Result,'abc',1);
ShowMessage(result);

result := 'DECLARE'''   #13#10   'DECLARE''''';
RegEx := TRegEx.Create('\A\s*DECLARE''\s*', [roIgnoreCase]);
Result := RegEx.Replace(Result,'',1);
ShowMessage(result);

This then returns abcDECLARE'' for abc replacement string and DECLARE'' for empty replacement string.

  • Related