Reputation: 12273
I was trying to change color to some text in a document, and I required regexp.
So, I tried the function findText
to search where my text is in the selected text, but I am having some troubles matching the regexps.
Look at this sample script
function onOpen() {
DocumentApp.getUi().createMenu('Test')
.addItem('Find regex in sel', 'findRegex'))
.addToUi();
}
function findRegex() {
var ui = DocumentApp.getUi();
var selection = DocumentApp.getActiveDocument().getSelection();
var txt = selection.getSelectedElements()[0].getElement().asText();
var inp = ui.prompt('Regex to search:').getResponseText();
var regex = new RegExp(inp);
ui.alert('Found in "' + txt.getText()
+ '"\n Re: ' + txt.findText(regex)
+ '\n In: ' + txt.findText(inp));
}
This prompts for something to search, then builds a regex out of it. Then both the regex and the original string are used to search in the selected text.
Well, I do not know what to do to get the regex
matching: I am always getting null: if the text to be searched is "foobarbaz", and I input foo
, only the plain string matches.
If instead I input /foo/
, clearly nothing matches.
How should I use regexps to search using findText
?
Consider that I have to "compose" regex, like /foobar/ + /\d+/
, where foobar
is the user-entered pattern.
Upvotes: 2
Views: 535
Reputation: 12273
Ok, I think to have found the crux: the regexp passed to findText
is always a String object, even if it have a regexp inside.
I tried searching "fo+"
in the text "fooo"
and it matched correctly.
Upvotes: 3