google-apps-script - 正则表达式从电子邮件中提取匹配的文本和任何数字
问题描述
我想从收到的电子邮件中提取像“SPR 0002745”这样的订单号(以“SPR”开头加一个空格,后跟一个 7 位数字 - 前面有零)。我将在 Gmail 中“加星标”并将电子邮件标记为“重要”。然后我将运行以下函数。
我想提取在电子邮件中找到的金额(一个数字 - 可能带有逗号,可能带有小数)。
我无法使用正则表达式。获取 null 作为输出。
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var filter = "label:inbox has:nouserlabels is:important in:Starred";
var threads = GmailApp.search(filter);
if (threads.length == 0) {
ss.toast("No message without label, marked star and important", "Remove label, mark star and important first", -1);
return;
}
for (var i = 0; i < threads.length; i++) { // Loop through the threads
var thisThread = threads[i]; // Get a speific thread
var messages = thisThread.getMessages(); // Get the messages in that thread
var messageCount = thisThread.getMessageCount(); // Count the number of messages in that thread
var lastMessage = messages[messageCount - 1]; // Get the last message in that thread. The first message is numbered 0.
break;
}
var message = lastMessage;
var body = message.getPlainBody();//body field
Logger.log(body);//working
var complaintno = body.match(/^SPR\ (.*)$/)
Logger.log(complaintno); //returnig null
var amount1 = body.match(/^-?(?:\d+|\d{1,3}(?:,\d{3})+)(?:(\.|,)\d+)?$/);
var amount2 = body.match(/^([0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?|\.[0-9]+)$/);
Logger.log(amount1);//returnig null
Logger.log(amount2);//returnig null
解决方案
这应该与您描述的订单号匹配var complaintno = body.match(/SPR \d{7}/)
:(SPR后跟一个空格和七位数字)。例如:
function testRegex() {
const body = 'Exercitationem commodi enim hic sunt maiores. Aperiam sunt praesentium fugit rem nemo et accusantium. Aut ab est sit mollitia eaque. Aliquam hic vel ut tempore quo quia enim nostrum. Quia aut qui ex voluptatibus: SPR 0002745 Ullam vel asperiores ut suscipit repellat. Velit porro qui et sunt et ea doloremque. Ipsum modi in dolores rerum.';
const complaintNumber = body.match(/SPR \d{7}/)[0];
Logger.log(complaintNumber); // This outputs SPR 0002745
}
推荐阅读
- python - 使用 BeautifulSoup 进行网页抓取,单击隐藏选项卡的元素
- html - 标签不跟随数据循环
- shell - Shell 脚本 - 从返回的块中获取指定的值
- c++ - 如何根据命令行更改 codelite 编译器设置
- arrays - Numpy:如何切片或拆分 2D 数组的 2D 小节
- python - 使用 CDK 部署时如何使用 pip 缓存?
- flutter - 找不到 Chrome。尝试将 CHROME_EXECUTABLE 设置为 Chrome 可执行文件。颤振 2.0
- python - 当机器人应用程序是在单独的帐户下创建时,如何从我的机器人帐户发送推文?
- spring-boot - 用户缺少权限或找不到对象:
我正在尝试使用如下存储过程填充 Spring Boot 嵌入式 HSQLDB 中的数据。
schema.sql 文件内容:
CREATE TABLE COUNTRY (NAME CHAR(6) NOT NULL, ID INT NOT NULL, PRIMARY KEY (ID)); CREATE PROCEDURE ACC_DETAILS(OUT newid INT, IN firstn
- flutter - 颤振菜单导航器循环