背景(可选):我在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
}
解决方法:
这里有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