splitting up text with a regular expression in google app script (documentApp) with findText

佐手、 提交于 2020-11-29 10:34:35

问题


In a google doc (not a spreadsheet) I have a wall of text that looks like

 °foo bar header°foo bar bat paragraph°and another paragraph°and yet an other paragraph°and so on

and I want to split up the text into paragraphs.

So I would like to get the text between the ° chars with help of a regexp. I would like to use

     var rangeElement = body.findText("°([^°]*)°");

but that regexp makes google docs go "Service unavailable: Docs". Using a regexp like "°.?°" alleviates that problem, but does not isolate the text I want.

What is a regexp that would work? How can I proceed to process the substring from within the ( and )?


回答1:


To get all (multiple) matches, you can leverage the JavaScript RegExp witha g (global) modifier.

var rx = /°([^°]*)/g;
while (m=rx.exec(doc.getBody().getText())) { 
    Logger.log("Matched: " + m[1]);
}

The /°([^°]*)/g is a regex literal notation (mind there should be no quotes around it), where / are regex delimiters, °([^°]*) is the pattern matching ° symbol and then capturing into Group 1 any 0 or more chars other than ° (([^°]*)) any number of times (g).

To actually match all the occurrences, you need to call RegExp#exec multiple times and grab Group 1 value (m[1]).



来源:https://stackoverflow.com/questions/44875634/splitting-up-text-with-a-regular-expression-in-google-app-script-documentapp-w

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!