Renumber Tokens using RegEx and findReplace

Renumber Tokens using RegEx and findReplace

1

    Aug 11, 2023#1

    In case anyone has the same problem, I post my solution to renumbering tokens in a text using regex and script.

    The job is to renumber Token-IDs given as "TokenId="<n>"".

    The solution ist quite simple.
    First replace all "<n>" to "X", then replace the "X" one by one with a number incremented on each step.

    The example is based on some general examples about findReplace. Unfortunately I lost the source url. Many thanks nevertheless!

    If there is already a similar solution on the forum, I apologize to have missed it. Then this post might be a duplicate.

    Code: Select all

    if (UltraEdit.document.length > 0)  // Is any file opened?
    {
       // Define environment for this script.
       UltraEdit.insertMode();
       // The first line is for UE/UES for Windows and the second line for UE for Linux/Mac.
       if (typeof(UltraEdit.columnModeOff) == "function") UltraEdit.columnModeOff();
       else if (typeof(UltraEdit.activeDocument.columnModeOff) == "function") UltraEdit.activeDocument.columnModeOff();
    
       // Move caret to top of the active file.
       UltraEdit.activeDocument.top();
    
       // Define the parameters for a case-sensitive Perl regular expression
       // replace all and run the replace on entire file.
       UltraEdit.perlReOn();
       UltraEdit.activeDocument.findReplace.mode=0;
       UltraEdit.activeDocument.findReplace.matchCase=true;
       UltraEdit.activeDocument.findReplace.matchWord=false;
       UltraEdit.activeDocument.findReplace.regExp=true;
       UltraEdit.activeDocument.findReplace.searchDown=true;
       UltraEdit.activeDocument.findReplace.searchInColumn=false;
       UltraEdit.activeDocument.findReplace.preserveCase=false;
       UltraEdit.activeDocument.findReplace.replaceAll=true;
       UltraEdit.activeDocument.findReplace.replaceInAllOpen=false;
       UltraEdit.activeDocument.findReplace.replace("TokenId=\"\\d+\"", "TokenId=\"X\"");
       var n = 1;
       UltraEdit.activeDocument.findReplace.replaceAll=false;
       while (true)
       {
        if (!UltraEdit.activeDocument.findReplace.replace("TokenId=\"X\"", "TokenId=\"" + n + "\""))
           break;
        n++;
       }
       
       
    }
    Greetings
    Bernd