Forum Discussion

subbu_valliappa's avatar
subbu_valliappa
Contributor
8 years ago
Solved

Search and Replace to include multiple lines (using DelphiScript)

I have these two lines in a text file:

 

string1

string2

 

I want to find these two lines and replace with a single line:

 

string3

 

The scripts that I have is as follows:

 

//Create a regular expression

regEx := HISUtils.RegExp;

//Set regular expression pattern

regEx.Expression := 'string1(\r\n)string2';

//Read from file

fileText := aqFile.ReadWholeTextFile(srcFile, aqFile.ctANSI);

//Perform replace operation

fileMod := regEx.Replace(fileText, 'string3');

//Write back to file

aqFile.WriteToTextFile(srcFile, fileMod, aqFile.ctANSI, true);

 

Search and replace does not happen with the above codes. If the string that I want to replace is within a single line, it all works fine but does not work when it involves multiple lines. The issue is definitely to do with multiple lines of text but I am not sure how can I detect this?

 

Any help would be much appreciated.

 

 

  • joseph_michaud's avatar
    joseph_michaud
    8 years ago

    The file contains only newlines (and no carriage returns).  Change your search expression to either of the following

     

    runlogRegEx.Expression := 'string1'+#10+'string2';
    ...
    runlogRegEx.Expression := 'string1\nstring2';

     

    The regular expression syntax used by HISUtils.RegExpr is more completely described here:

     

    Tokens Used in Native Regular Expressions

8 Replies

  • YuriPeshekhonov's avatar
    YuriPeshekhonov
    SmartBear Alumni (Retired)

    Hi,

     

    Please try using the following expression:

     

    regEx.Expression := 'string1'+#13#10+'string2';

     

    Also, I have noticed that there is a typo in your code. The name of the object is "HISUtils.RegExpr":

     

    regEx := HISUtils.RegExpr;

    • subbu_valliappa's avatar
      subbu_valliappa
      Contributor

      Tried with #13#10 but this didn't work either.

       

      This is the full procedure:

       

       

      procedure FindAndReplaceInFile(srcFile);
      var
        runlogRegEx, resFileMod, resFileText;
       
      begin
       
        //Create regular expression
        runlogRegEx := HISUtils.RegExpr;
       
        //Set regular expression pattern
        runlogRegEx.Expression := 'string1'+#13#10+'string2';
       
        //Read from file
        resFileText := aqFile.ReadWholeTextFile(srcFile, aqFile.ctANSI);
       
        //Replace the matching text
        resFileMod := runlogRegEx.Replace(resFileText, 'string3');
       
        //Write back to file
        aqFile.WriteToTextFile(srcFile, resFileMod, aqFile.ctANSI, true);
       
      end;

       

      • joseph_michaud's avatar
        joseph_michaud
        Moderator

        I used your code.  Works for me.

        Make sure that the encoding of your text file truly is ANSI.

        What version of TestComplete are you using?