后台(可选):我在VBA中编写了一个工作脚本,我正在尝试用JS编写Google Spreadsheets,但我在使用正则表达式验证时遇到了很大的困难。每个单元格。
在这个VBA代码片段中,我设置了一系列数据,并根据先前定义的RegEx测试每个单元格。
Set rRange = Range(arrLetters1(i) & intRange1, arrLetters2(i) & intRange2)
For Each rCell In rRange.Cells
If re.Test(rCell) Then
rCell.Interior.Color = RGB(0, 250, 0)
Else
Cells((intRange1 - 1), rCell.Column).Interior.Color = RGB(250, 0, 0)
rCell.Interior.Color = RGB(250, 0, 0)
End If
Next rCell
我很好奇的是,实际的 JavaScript 功能可以让我查看相同的范围并执行相同的操作。这就是我所拥有的:
var re = "[a-z]+"
var rRange = sheet.getRange(arrLetters1(i) + intRange1, arrLetters2(i) + intRange2)
for (var rCell in rRange) {
if (rCell //is a "re" match) {
//do some code
}
} else {
//do something else
}
答案 0 :(得分:2)
这里有2个如何在JS中使用RegEx的示例,WScript.Echo是JScript,以便于测试,替换为document.write或response.write或其他
var rRange = "this string is for testpurposes"
var re = /[a-z]+/
var regExp = new RegExp(re);
if (rRange.match(regExp)) {
WScript.echo("Successful match");
} else {
WScript.echo("No match");
}
=>Successful match
var str="The rain in SPAIN stays mainly in the plain";
var n=str.match(/ain/g);
WScript.echo(n);
=> ain,ain,ain
答案 1 :(得分:2)
好的,快速查看一下,看起来你想检查一系列单元格中的值,将它们与正则表达式进行比较,并根据结果更改单元格颜色。请记住,之前我没有使用过谷歌文档API,看起来你的现有代码只有一些小问题。
首先,您需要正确创建正则表达式。
你的专栏:
var arrPatterns = new Array("^([A-Z]{2}(-[0-9]{5}){4})$", "^[A-Z]{2}$", "^[0-9]{5}$", "^[a-z]{1,}$", "^\(\d\d\d\) \d\d\d-\d\d\d\d$", "^([a-z0-9]{1,}[,]{0,}){1,}$", "^(\d\d?:\d\d[aApP][mM] - \d\d?:\d\d[aApP][mM])|(Closed)|(All Day)$");
变为:
var arrPatterns = [/^([A-Z]{2}(-[0-9]{5}){4})$/, /^[A-Z]{2}$/, ... /^(\d\d?:\d\d[aApP][mM] - \d\d?:\d\d[aApP][mM])|(Closed)|(All Day)$/];
有两个更改正在删除new Array
,只支持使用[ ]
的文字数组语法(可选但考虑好的做法),并用正斜杠替换数组字符串中的引号(正则表达式文字语法)。结果是一个正则表达式对象数组而不是字符串。这样您就可以像在评估代码中那样执行re.test("some string");
之类的操作。
其次,您需要循环遍历单元格范围,获取其值并进行比较。快速检查documentation告诉我sheet.getRange
返回Range
个对象。 range对象有一个getValues
方法,它返回一组单元格值数组(array [] [])。
因此,您可以快速找到所需内容的代码:
var rRange = sheet.getRange(arrLetters1(i) + intRange1, arrLetters2(i) + intRange2);
var values = rRange.getValues();
var re = arrPatterns[0];
var row, col;
for (row = 0; rows < values.length; row++) {
for (col = 0; col < values[row].length; col++) {
if (re.test(values[row][col])) {
/*do passes regex, looks like you probably need to pass the row/col to getCell
to get a range with the desired cell in it and then call setBackgroundColor on
that range. I'm also leaving looping through your array of regular expressions to you,
as it looked like you have a dependency on the expression being used and the array of
letters i didn't take the time to understand.*/
}
else {
//do fails regex
}
}
}