简体   繁体   English

正则表达式 - 谷歌应用程序脚本

[英]Regex - google apps script

I'm trying to extract a substring of a email document with a regular expression.我正在尝试使用正则表达式提取电子邮件文档的子字符串。 I'm testing the regex online, and it works perfectly:我正在在线测试正则表达式,它运行良好:

online regex tester在线正则测试仪

I have a function to check the regex on Google Apps Script and the same regex isn't working here.我有一个函数可以检查 Google Apps Script 上的正则表达式,但相同的正则表达式在这里不起作用。

var regex = new RegExp("Intrusion signature\(s\)\:\n\n(.*)");
var e = regex.exec(data);

Google Apps Script code Google Apps 脚本代码

Logger记录器

Does anyone knows why is not working?有谁知道为什么不工作?

Using a literal regex instead of converting the string to a regex works.使用文字正则表达式而不是将字符串转换为正则表达式是可行的。

var regex = new RegExp(/Intrusion signature\(s\)\:\n\n(.*)/);

在此处输入图片说明

When you use regular strings with RegExp you need to escape every backslash.当您将常规字符串与 RegExp 一起使用时,您需要对每个反斜杠进行转义。 Here are some alternatives you can use.以下是您可以使用的一些替代方法。 Another aspect to consider is that if you have CR+LF in your Spreasheet.要考虑的另一个方面是,如果您的电子表格中有 CR+LF。 In that case you need to change your code to include \\r I've added some google API mocked code so that the code snippet can run here在这种情况下,您需要更改代码以包含 \\r 我添加了一些 google API 模拟代码,以便代码片段可以在此处运行

 // ----------------- Ignore this (Mock) Logger=console; class _SpreadsheetApp { getActiveSpreadsheet() { class SpreadSheet { getSheetByName(name) { class Sheet { getRange() { class Range { getValue() { return " * Intrusion signature(s):\\r\\n\\r\\n - This is the text I want to extract.\\r\\n\\r\\n * SI communication:\\r\\n"; } } return new Range(); } } return new Sheet(); } } return new SpreadSheet(); } } var SpreadsheetApp=new _SpreadsheetApp(); // ----------------- Ignore this (Mock) function checkRegExp() { var data=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("LOG").getRange("C213").getValue(); var regex = new RegExp("Intrusion signature\\(s\\)\\:\\n\\n(.*)"); // ORIGINAL var e = regex.exec(data); Logger.log("Original:"+e); var sol1 = new RegExp("Intrusion signature\\\\(s\\\\)\\\\:\\\\r\\\\n\\\\r\\\\n(.*)"); e = sol1.exec(data); if (e) Logger.log("Solution 1:"+e[1]); var sol2 = new RegExp("Intrusion signature\\\\(s\\\\)\\\\:\\\\W{2,4}(.*)"); e = sol2.exec(data); if (e) Logger.log("Solution 2:"+e[1]); var sol3 = new RegExp("Intrusion signature\\\\(s\\\\)\\\\:(?:\\\\x0d\\\\x0a)+(.*)"); e = sol3.exec(data); if (e) Logger.log("Solution 3:"+e[1]); var sol4 = new RegExp(/Intrusion signature\\(s\\)\\:\\r\\n\\r\\n(.*)/); e = sol4.exec(data); if (e) Logger.log("Solution 4:"+e[1]); } checkRegExp()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM