我正在尝试使用Google Docs文档中的一些正则表达式突出显示一些文本(在下面的示例中,我想强调“ORGANIZA”),但我无法使第一个工作成为一个简单的正则表达式来查找“ category_name“string。
为什么:
function highlightTextTwo() {
/* DOCUMENT DEFINITION */
var doc = DocumentApp.openById('1M6JmJPndLS_hkdaUo5holsdxB5GSSrcWMa1j4Hh7Dig');
/* VARIABLE DEFINITION */
var highlightStyle = {};
var paras = doc.getParagraphs();
var textLocation = {};
var i;
/* REGEX DEFINITION */
var MyRegex = new RegExp('category_name','i');
/* COLOR STYLE DEFINITION */
highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000';
/* CODE */
for (i=0; i<paras.length; ++i) {
Logger.log( paras[i].findText(MyRegex) );
}
}
适用于本文件:
{
"map_image": "mapa_con_close_button.png",
"categories":[
{
"category_id": 1,
"category_name": "ORGANIZA",
"color": "#4591D0",
"icon_image": "Organiza.png"
},
{
"category_id": 2,
"category_name": "DELEGA",
"color": "#94C5DD",
"icon_image": "Delega.png"
},
{
"category_id": 3,
"category_name": "NEGOCIA Y GESTIONA EL CONFLICTO",
"color": "#E7344A",
"icon_image": "Negocia_y_Gestiona.png"
}
返回:
[15-06-03 20:12:48:026 CEST] null
[15-06-03 20:12:48:027 CEST] null
[15-06-03 20:12:48:028 CEST] null
[15-06-03 20:12:48:029 CEST] null
[15-06-03 20:12:48:030 CEST] null
[15-06-03 20:12:48:030 CEST] null
而是一些空值和一个“category_name”。
答案 0 :(得分:3)
我找到了一种显示所有category_name
字符串的方法。要点:
exec
循环中使用RegExp while
而不是findText
g
标记和regex getText()
代码:
var paras = doc.getParagraphs();
var MyRegex = new RegExp('category_name','ig');
for (i=0; i<paras.length; ++i) {
while (match = MyRegex.exec(paras[i].getText()))
{
Logger.log(match[0]);
}
}
日志中的输出:
[15-06-04 21:07:36:320 CEST] category_NAME
[15-06-04 21:07:36:322 CEST] category_name
[15-06-04 21:07:36:324 CEST] category_name
修改强>:
这是一种用红色突出显示匹配的方法:
var paras = doc.getParagraphs();
var MyRegex = new RegExp('category_name','ig');
for (i=0; i<paras.length; ++i) {
while (match = MyRegex.exec(paras[i].getText()))
{
var searchResult = paras[i].findText(match[0]);
if (searchResult !== null) {
var thisElement = searchResult.getElement();
var thisElementText = thisElement.asText();
thisElementText.setBackgroundColor(searchResult.getStartOffset(), searchResult.getEndOffsetInclusive(),"#FF0000");
}
}
}