如何使此Google脚本代码重复性更低?

时间:2019-06-30 00:00:28

标签: javascript optimization google-apps-script

我有以下代码是我从Google脚本帮助文件中复制/粘贴/修改的:

function DHGreen() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("D3:P43");
var rule = SpreadsheetApp.newConditionalFormatRule()
    .whenTextEqualTo("DH")
    .setBackground("#00ff00")
    .setRanges([range])
    .build();
var rule2 = SpreadsheetApp.newConditionalFormatRule()
    .whenTextEqualTo("Mazie")
    .setBackground("#0000ff")
    .setRanges([range])
    .build();
var rule3 = SpreadsheetApp.newConditionalFormatRule()
    .whenTextEqualTo("Herald")
    .setBackground("#9900ff")
    .setRanges([range])
    .build();
var rules = sheet.getConditionalFormatRules();
rules.push(rule);
rules.push(rule2);
rules.push(rule3);
sheet.setConditionalFormatRules(rules);
}

我觉得应该有一种方法可以更有效地执行此操作,但是由于我仍处于复制/粘贴状态,因此请更改内容并希望它仍能在学习Google脚本(对VBA更为熟悉)的阶段中起作用,我只是不确定从哪里开始。任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

您可以使用函数来创建规则,而不必重复执行该代码。

import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "^(?=(?!prefix)(suffix))\\1+$";
final String string = "prefixsuffix\n"
     + "prefixsuffixsuffix\n"
     + "prefixsuffixsuffixsuffix\n\n"
     + "suffix\n"
     + "suffixsuffix\n"
     + "suffixsuffixsuffix";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println("Full match: " + matcher.group(0));
    for (int i = 1; i <= matcher.groupCount(); i++) {
        System.out.println("Group " + i + ": " + matcher.group(i));
    }
}