我有一个包含text(var A1String)
的colRegenerist Anti Aging Micro Sculpting Serum
Meghalaya Grass&塑料(棕色和粉红色)
Meghalaya Grass&塑料(棕色和粉红色)
Dentastix大型品种(7片,成人)
5星Magic Pro-Health Chocolate(补充装)
在Search_Keys(var repstring)中单独的col I键 - 例如
"抗衰老精华素"
" 5颗巧克力"
我正在尝试将我的键入条目转换为带有狂野字符的正则表达式,以避免" Micro Sculpting"在第1行,或者#34; Magic Pro-Health"在第5行。
我尝试了以下代码:
var split_repstring = repstring.split(' ');
var regex_repstring = new RegExp(split_repstring[0]+"\\?",'g');
for (var e=1;e<split_repstring.length;e++)
{regex_repstring=new RegExp(regex_repstring+split_repstring[e]+("\\?"),'g');}
然后按如下方式搜索我的表(A1String):
var a = A1String.search(regex_repstring);
记录器输出为:
[18-06-15 10:16:58:090 PDT] [Anti, Ageing, Serum]
[18-06-15 10:16:58:091 PDT] 3.0
[18-06-15 10:16:58:092 PDT] ///Anti\?/gAgeing\?/gSerum\?/g
不用说,搜索没有返回预期的结果。
有人能指导我吗?
提前致谢
答案 0 :(得分:0)
您可以使用String.prototype.replace()构建我认为您正在寻找的正则表达式。
new RegExp(repstring.replace(/ /g, ' .*'))
我创建了一个测试表:
+-------------------------------------------------+-------------------+
| 1. Regenerist Anti Ageing Micro Sculpting Serum | Anti Ageing Serum |
| 2. Meghalaya Grass & Plastic (Brown & Pink) | 5 Star Chocolate |
| 3. Meghalaya Grass & Plastic (Brown & Pink) | |
| 4. Dentastix Large Breed Treat (7 Pcs, Adult) | |
| 5. 5 Star Magic Pro-Health Chocolate (Refill) | |
+-------------------------------------------------+-------------------+
这是使用上述方法的脚本:
function search() {
var sheet = SpreadsheetApp.getActiveSheet();
var data = sheet.getRange(1, 1, 5).getValues()
var queries = sheet.getRange(1, 2, 2).getValues();
var queryRegexes = [];
for (var i = 0; i < queries.length; i++) {
queryRegexes[i] = new RegExp(queries[i][0].replace(/ /g, ' .*'));
}
for (var i = 0; i < queryRegexes.length; i++) {
Logger.log('Results for ' + queryRegexes[0]);
Logger.log(data.filter(function(entry) {
return queryRegexes[i].test(entry);
}));
}
}
这是记录输出:
[18-06-15 11:28:11:387 PDT] Results for /Anti .*Ageing .*Serum/
[18-06-15 11:28:11:388 PDT] [[1. Regenerist Anti Ageing Micro Sculpting Serum]]
[18-06-15 11:28:11:389 PDT] Results for /Anti .*Ageing .*Serum/
[18-06-15 11:28:11:389 PDT] [[5. 5 Star Magic Pro-Health Chocolate (Refill)]]