0

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.

1
  • So, \A works as (?m)^, it looks like a bug. Commented Oct 19, 2022 at 21:17

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your answer. Your solution works. However, in my question, the \A part of the regex should only replace from the beginning of the string, even you replace all the matches. The behavior still looks weird to me.
That is because for replace it runs against the full modified string to find the next match. Once the first DECLARE' is replaced the second is now just whitespace away from the start of the string so it now matches and gets replaced as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.