【问题标题】:Capture value in a variable using regEx and findText使用 regEx 和 findText 捕获变量中的值
【发布时间】:2018-01-19 23:56:48
【问题描述】:

我正在尝试从该行中捕获数字 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 不支持捕获组,还有其他方法可以捕获模式吗?提前致谢!

【问题讨论】:

  • 请简要说明您在正则表达式方面的搜索/研究工作。参考How to Ask.
  • 感谢@Rubén 的建议,我已经更新了问题。

标签: regex google-apps-script google-docs


【解决方案1】:

这就是我最终的结果,感谢@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);
}

【讨论】:

    【解决方案2】:

    您可以尝试分两步完成

    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,我最终使用了我们的建议,并进行了如下所示的一些调整:
    猜你喜欢
    • 2014-11-08
    • 1970-01-01
    • 2015-04-27
    • 2012-01-21
    • 2011-01-18
    • 2011-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多