0

In javascript, I use the next code to strip off linefeeed and carriage return of a string and it works well:

var values="something....."
var sanit=values.replace(/(\r?\n|\r\n?)/g, "");

In Delphi, I am trying the next code:

values="something....."
sanit:=TRegex.Replace(values,'/(\r?\n|\r\n?)/g', '');

But it doesn´t work. No replace is done.

6
  • Find out if Delphi uses delimiters in regex. and about language escaping, and parameter order of the replace. Also, if the replace automatically replaces all (don't need g)
    – user557597
    May 7, 2019 at 16:03
  • 1
    Delphi uses PCRE I believe. Read the docs on that regex flavour. May 7, 2019 at 16:04
  • Also, this regex is sufficient (?:\r?\n|\r)+
    – user557597
    May 7, 2019 at 16:06
  • 2
    Why use a regex if StringReplace will do? ISTM that it should be a little faster and simpler to use. May 7, 2019 at 16:13
  • 2
    Why not use the SysUtils.StringReplace? sanit := StringReplace(values,#$D#$A,'',[rfReplaceAll]);
    – LU RD
    May 7, 2019 at 16:13

1 Answer 1

7

You don't necessarily need RegEx for this task. This can also be done with the function StringReplace:

StringReplace(value, sLineBreak, '', [rfReplaceAll])

or

StringReplace(StringReplace(value, sLineBreak, '', [rfReplaceAll]), #10#13, '', [rfReplaceAll])

to replace both combinations of #10 (\n) and #13 (\r).

Constant sLineBreak is located in unit System and is declared as #13#10 (or in Hex: #$0D#$0A), when the selected target platform is Windows.

2
  • Or just use Trim if specifically looking to remove whitespace and control characters from only the start and end of the string.
    – J...
    May 7, 2019 at 16:48
  • Thank you, as I am working in a front end using JS I tried make the similar code in delphi.It seems TRegex.Replace(values,'\R', '') works well. But your solution works as well
    – Luiz Alves
    May 7, 2019 at 16:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.