Hugues Van Landeghem
Hugues Van Landeghem

Reputation: 6808

Delphi TRegEx Replace

I want to replace character in a big string all character @ by #13#10 if they match the pattern.

But how to get my the value of '[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' of my pattern to put in my replacement field ?

pattern := '@' + '[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' + '\$';
replacement := #13#10 + '[0-9][0-9][0-9][0-9][0-9][0-9][0-9]' + '\$';
ts.Text := TRegEx.Replace(AString, pattern, replacement, [roIgnoreCase]);

Upvotes: 6

Views: 10396

Answers (2)

Robin
Robin

Reputation: 9644

To perform your check you can use a positive lookahead:

pattern := '@(?=[0-9]{7}\$)'
replacement := #13#10

The (?=...) will check the @ is followed by what you want, without selecting these following digits.

Upvotes: 18

David Heffernan
David Heffernan

Reputation: 612924

You can do it like this:

TRegEx.Replace(s, '@([0-9]{7}\$)', #13#10+'\1')

To break it down:

  • [0-9]{7} means 7 occurrences of a digit.
  • The parens (...) are used to capture the 7 digits and the $.
  • The \1 in the replacement string expands to the captured string.

Although Robin's approach is nicer!

Upvotes: 6

Related Questions