Home > database >  Regex that had been working in Google App scripts has suddenly starting returning only null
Regex that had been working in Google App scripts has suddenly starting returning only null

Time:01-06

I have an app script that uploads a file to a specific drive in Google Drive. In the script, I try to normalize the file name by removing any prefixes or suffixes that might be have been added to the original file name as a result of copying or downloading it on the part of the user.(ie. Excel Filename (1).xlsx, or Copy of Excel File Name.xlsx will parse out only Excel Filename and exclude the (1) or Copy of)

A sample file name for this process would be: Request ID - NPRl8501P24 Auburn Memorial Hospital Add User Template.xlsx.

The "Request ID - NPR" is a constant in all filenames, anything between that and the word Template is variable.

I created a regex to pull all that information and use it as the filename (thus, excluding any prefixes or suffixes to the filename and it had been working up until yesterday (with no changes to the code) when the regex started to return null, and I am at a loss as to why.

This is the code that had been working but suddenly stopped. Any help would be appreciated

    function UploadApprovalFilesToGoogleDrive(approveddata,approvedname,approvedtype){                                     
    Logger.log(approvedname)
    var string = (approvedname);
    var regexp = /Request ID - NPR.*\sTemplate/
    var parsedName =regexp.exec(string)
    Logger.log(parsedName)

CodePudding user response:

The regex /Request ID - NPR.*\sTemplate/ matches the text string Request ID - NPRl8501P24 Auburn Memorial Hospital Add User Template.xlsx. It is unclear what the problem is.

To make your regex a bit more flexible to variation in spacing and letter case, use \s* in place of space and the /i modifier, like this:

  const string = 'Request ID - NPRl8501P24 Auburn Memorial Hospital Add User Template.xlsx';
  const regex = /(Request\s*ID\s*-\s*(. ?)\s*Template)/i;
  const parsedName = string.match(regex);
  if (!parsedName) {
    console.log(`regex '${regex.toString()}' does not match the text string '${string}'`);
  } else {
    console.log(`full parsedName result: '${JSON.stringify(parsedName)}'`);
    console.log(`extract filename without prefixes and suffixes: '${parsedName[1]}'`);
    console.log(`extract variable part: '${parsedName[2]}'`);
  }

See regular expression quickstart.

  • Related