skip to Main Content

i was trying to get an expression for google script for a google document that i cant get. I want to find all occurences of words that are: “X-X-Xr”
Where “X” is a capital letter or number, “-” it is literally -, and “r” is literally r. I want to find all occurences and then highlight them. The word could be between two blank spaces, or right after a “:”

2

Answers


  1. Try this:

    function search4Files() {
      let fs = DriveApp.getFilesByType(MimeType.GOOGLE_DOCS);
      let files = [];
      while(fs.hasNext()) {
        let file = fs.next();
        files.push(file);
      }
      if(files && files.length > 0) {
        let f = files.filter(f => f.getName().match(/([A-Z])-1-1r/g)).map(f => [f.getName(),f.getId()]);
        Logger.log(JSON.stringify(f));
      }
    }
    

    I created a file named X-X-Xr and ran the code.

    Execution log
    10:27:03 AM Notice  Execution started
    10:27:04 AM Info    [["X-X-Xr","1WPtB9mdWZsWHEARvHuWdBOld8ay0k9hLTjhkurLe7-E"]]
    10:27:06 AM Notice  Execution completed
    

    You could post files into a sheet with a setValues if you wish.

    Login or Signup to reply.
  2. Using Regxr and Body.findText() you should be able to find the strings you want.

    enter image description here

    Here is a sample code for Google Doc for the same text shown above.

    function test() {
      try {
        let doc = DocumentApp.getActiveDocument();
        let body = doc.getBody();
        let find = body.findText("(\S-){1,}\Sr");
        let style = {};
        style[DocumentApp.Attribute.FOREGROUND_COLOR] = "#0000FF";  // blue
        while( find ) {
          let element = find.getElement().asText();
          element.setAttributes(find.getStartOffset(),find.getEndOffsetInclusive(),style);
          find = body.findText("(\S-){1,}\Sr",find);
        }
      }
      catch(err) {
        console.log(err)
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search