Google Apps脚本突出显示多项选择 [英] Google Apps Script to highlight multiple choice

查看:64
本文介绍了Google Apps脚本突出显示多项选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个Google Apps脚本,以突出显示Google文档中的多项选择答案.这是一个示例问题:

I'm trying to make a Google Apps Script that will highlight multiple choice answers in a Google Doc. Here's an example question:

Question....blah blah blah.
a. Answer 1
b. Answer 2
c. Answer 3
d. Answer 4
e. Answer 5

这是到目前为止我对脚本的了解:

And here's what I've got so far for a script:

function highlight() {
  var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1nP6ra0zIMI3OB-zsTMbFybO2e7ajoYgQi8doDcurGew/edit?usp=sharing');
  var style = {};
  style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#E3E65B';
  var text = doc.editAsText();
  var result = text.findText(/^(a|b|c|d|e)\..*/gm).getElement();
   for (var i = 0; i < result.length; i++){
   result[i].setAttributes(style);
   }
}

但这只是给我不能调用null的方法"getElement"."

But it just gives me "Cannot call method "getElement" of null".

推荐答案

您不会期望没有匹配的结果.试试这个吧.

You are not expecting a no matched result. Try this instead.

function highlight() {
  var doc = DocumentApp.openByUrl('https://docs.google.com/document/d/1nP6ra0zIMI3OB-zsTMbFybO2e7ajoYgQi8doDcurGew/edit?usp=sharing');
  var style = {};
  style[DocumentApp.Attribute.BACKGROUND_COLOR] = '#E3E65B';
  var text = doc.editAsText();
      if(text.findText(/^(a|b|c|d|e)\. Answer [0-9]+$/gm) !== "undefined")
      {   
         var result = text.findText(/^(a|b|c|d|e)\. Answer [0-9]+$/gm)).getElement();
         for (var i = 0; i < result.length; i++)
         {
           result[i].setAttributes(style);
         }
      } 
      else 
      {
        //Do whatever. There is no element matched
      }
}

另一方面,正则表达式/^(a|b|c|d|e)\..*/gm表示:

On the other hand, the regex /^(a|b|c|d|e)\..*/gm means:

a OR b OR c OR d OR e.,任何字符0或更多次(.*)开头. g标志意味着它将在第一个匹配项之后继续搜索. m标志表示$^可以分别匹配行的开头和行的结尾.

Begins with a OR b OR c OR d OR e, ., any character 0 or more times (.*). g flag means that will continue searching after the first match. The m flag means that $ and ^ can match the beginning of a line and the end of a line respectively.

因此它将与以下内容匹配:a.anythingb.66/qQ-.r...等.

So it will match something like this: a.anything, b.66/qQ-.r..., etc.

如果要匹配a. Answer 1之类的内容,则应使用:

If you want to match something like a. Answer 1, you should use:

/^(a|b|c|d|e)\.\s.+\s[0-9]+$/gm

如果要一直使用Answer,则可以使用:

If it is going to be always Answer you could use:

/^(a|b|c|d|e)\.\sAnswer\s[0-9]+$/gm

这篇关于Google Apps脚本突出显示多项选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆