javascript - Google Apps 脚本中的条件正则表达式

标签 javascript regex google-apps-script

我有一个 Google Apps 脚本 我需要提取 IP,问题是它们可能在同一行:

enter image description here

或者两行:

enter image description here

当 IP 位于同一行时,一切正常:

    function regtest (){

      //In this cell I have gmail content 
      var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LOG").getRange("C364").getValue();

      var regex = new RegExp(/\- Destination ip address\(es\):(.*)/);
      var e = regex.exec(data);
      Logger.log(e);
    }

但我不知道如何在不同行中提取 IP...

有人可以帮我吗?

最佳答案

我针对 进行了测试 - 目标 IP 地址:1.2.4.6、2.2.4.6、3.2.4.6,\n 4.2.4.6 字符串:

enter image description here

似乎以下工作:

function regtest (){
  //In this cell I have gmail content 
  var data = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LOG").getRange("C364").getValue();
  var regex = /- Destination ip address\(es\):((?:\s*,?\s*\d+(?:\.\d+){3})+)/;
  var m, res = [];
  m=regex.exec(data);
  if (m) {
     res = m[1].split(',').map(function (x) { return x.trim(); });
  }
  Logger.log(res);
}

结果:

enter image description here

基本上,((?:\s*,?\s*\d+(?:\.\d+){3})+) 捕获组匹配可选的 包含 0+ 个空格,然后将类似 IP 的子字符串分成 1 组,然后您只需要用 将其拆分, 并从空格中删除结果项。

关于javascript - Google Apps 脚本中的条件正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49069552/

相关文章:

javascript - 当不透明度为 0 时隐藏 div 中的可点击链接

javascript - Internet Explorer 9 和 10 全屏问题

javascript - 使用javascript代码动态地将多行和多列插入到html表格中

regex - 用于验证邮政编码格式的 dart 正则表达式

javascript - "Cannot set property ' jwtClient ' of undefined"尝试将 Node.js 与 Google 表格一起使用

javascript - 为什么我可以删除一个声明为 a = 1 的变量而不是一个在 javascript 中声明为 var b = 1 的变量

python - 如何在 Python 中从 yaml 转储中删除键/值对?

java - Java 中的正则表达式——只返回最后一个匹配项

javascript - 按背景颜色计算行数失败

google-apps-script - 如何在多个文档中使用Google Apps脚本