Apps Script Regex - Case Insensitive

2019-07-26 07:51发布

I am writing an apps script for Google Docs. I am using findText() to locate an instance of a specified string of characters.

By default, it is case sensitive and I need to remove that, but I can't figure out how to add the /i to the re2 regex so that it works in apps script engine.

In my example, I am trying for find all instances of micssys (e.g. micssys, Micssys, MICSSYS, etc).

Right now I have:

var text = "micssys";
var bodyElement = DocumentApp.getActiveDocument().getBody();
var searchResult = bodyElement.findText(text);

I have tried:

var searchResult = bodyElement.findText("/"+text+"/i");

var searchResult = bodyElement.findText(text+"/i");

var searchResult = bodyElement.findText(text+"(i)");

None of these work. What am I missing

1条回答
看我几分像从前
2楼-- · 2019-07-26 08:24

If I recall, I believe you can create a new regexp object and use exec here.

var re = new RegExp('\\bmicssys\\b','gi');

var match;
var bodyElement = DocumentApp.getActiveDocument().getBody();
while (match = re.exec(bodyElement)) {
   // match[0] will return the found results
}

Note: You may have to use getText() to retrieve the contents of the element as a text string and then match against.

查看更多
登录 后发表回答