Google Apps脚本突出显示多项选择 [英] Google Apps Script to highlight multiple choice
问题描述
我正在尝试制作一个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.anything
,b.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屋!