2013-06-29 75 views
1
function searchAndColorInRed() { 
    var doc = DocumentApp.getActiveDocument(); 
    var textToHighlight = new RegExp('\(\d{0,4}\)'); 
    var highlightStyle = {}; 
    highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000'; 
    var paras = doc.getParagraphs(); 
    var textLocation = {}; 
    var i; 

    for (i=0; i<paras.length; ++i) { 
    textLocation = paras[i].findText(textToHighlight); 
    if (textLocation != null && textLocation.getStartOffset() != -1) { 
     textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle); 
    } 
    } 
}; 

得到此函數搜索括號(6406)中的數字,但着色不起作用..我不知道爲什麼,有人可以幫助我嗎?在Google文檔中搜索和着色

+0

我無法得到它的工作之一...我只能得到在文檔中突出顯示的數字,這些數字有一個斜槓然後是數字然後是斜線,如下所示:/ 234/ –

+0

而且我還可以在dox中匹配以下文本:/(234)/ using regex/\ (\ d * \)/(但是,如上面的評論,不是(234) –

+0

我希望你能得到答案......我一直在嘗試你的代碼和其他方法的一些變體,但沒有成功。爲什麼: -/pourtant le rege x est正確...,怪異:-) –

回答

0

AdamL是對的。

我有點糊塗了,由於FINDTEXT方法的谷歌文檔的描述:

FINDTEXT(是searchPattern)

搜索元素的使用正則表達式指定的文本模式 內容

我也設法使用字符串轉義所有\

function searchAndColorInRed() { 
    var doc = DocumentApp.getActiveDocument(); 
    var textToHighlight = "\\(\\d{0,4}\\)"; 
    var highlightStyle = {}; 
    highlightStyle[DocumentApp.Attribute.FOREGROUND_COLOR] = '#FF0000'; 
    var paras = doc.getParagraphs(); 
    var textLocation = {}; 
    var i; 

    for (i=0; i<paras.length; ++i) { 
    textLocation = paras[i].findText(textToHighlight); 
    if (textLocation != null && textLocation.getStartOffset() != -1) { 
     textLocation.getElement().setAttributes(textLocation.getStartOffset(),textLocation.getEndOffsetInclusive(), highlightStyle); 
    } 
    } 
}; 

所以,是的,最終爲AdamL說,你可以使用'[(][0-9]{0,4}[)]'; 或者你可以用大衛曾提出,Mogsdad的劇本,似乎方便了什麼,我需要Can I color certain words in Google Document using Google Apps Script?