使用 regEx 和 findText 捕获变量中的值

Capture value in a variable using regEx and findText

我正在尝试从以下行中捕获数字 10.0006:

总时间:10.0006s

这是文本文件中的一行。到目前为止我有:

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);

根据 https://developers.google.com/apps-script/reference/document/text#findText(String) 的说法,findText 不支持捕获组,还有其他方法可以捕获模式吗?提前致谢!

您可以尝试分两步完成

  1. findText 找到需要的元素。
  2. 使用 JavaScript 的 match 和相同的正则表达式来匹配所需的字符组。

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);
}

这是我最终的结果,感谢@Kos 的帮助!

// 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);
}