0

I'm trying to capture the number 10.0006 from the line:

total time: 10.0006s

which is one line in a text file. So far I have:

var doc = DocumentApp.openByUrl('removed url').getBody().editAsText();

//locate totalTime text
var regEx = "/(?<=total time: )([\d\.]+[\d])(?=s)/";
var totalTime = doc.findText(regEx).getElement().getText();

//display values in log
Logger.log(totalTime);

According to https://developers.google.com/apps-script/reference/document/text#findText(String) capture groups are not supported with findText, are there any other ways to capture the pattern? Thanks in advance!

2
  • Please add a brief description of your search/research efforts about regular expressions. Reference How to Ask. Commented Jan 20, 2018 at 0:09
  • Thanks for the advice @Rubén, I have updated the question. Commented Jan 20, 2018 at 0:42

2 Answers 2

0

You can try do it with two steps

  1. find needed element with findText.
  2. use JavaScript's match with same regex to match needed group of characters.

var doc = DocumentApp.openByUrl('removed url').getBody().editAsText();

// locate totalTime text
var regEx = "total time: ([0-9.]+)s";
var foundRange = doc.findText(regEx);

// if range is found
if (foundRange)
{
  // get related element ant it's text
  var foundText = foundRange.getElement().getText();
  // capture needed group of characters
  var totalTime = foundText.match(regEx)[1];

  //display values in log
  Logger.log(totalTime);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Kos, I ended up using our suggestion with a few tweaks shown below:
0

Here's what I ended up going with, thanks @Kos for the help!

// locate totalTime text
    var findLine = "total time:";
    var foundRange = doc.findText(findLine);


// if range is found
if (foundRange)
{
  var regEx = /[\d\.]+[\d](?=s)/
  // get related element and it's text
  var foundText = foundRange.getElement().getText();
    Logger.log(foundText);
  // capture needed group of characters
  var totalTime = foundText.match(regEx);

  //display values in log
  Logger.log(totalTime);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.