Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi TRegEx Replace

Tags:

regex

delphi

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]);
like image 977
Hugues Van Landeghem Avatar asked Nov 29 '22 15:11

Hugues Van Landeghem


2 Answers

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.

like image 197
Robin Avatar answered Dec 06 '22 08:12

Robin


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!

like image 26
David Heffernan Avatar answered Dec 06 '22 08:12

David Heffernan