Reg Exp failure for open parenthesis - Error - Unterminated parenthetical

905 views
Skip to first unread message

Alan Wells

unread,
Jan 14, 2020, 4:26:29 PM1/14/20
to Google Apps Script Community
I'm trying to search for a function name with the following code and getting an error.  I want to include the first parenthesis in the search.

I'm getting the error:

SyntaxError: Unterminated parenthetical


  for (i = L-1;i>-1; i--){
    thisName
= allNames[i];//The function name
   
    re
= new RegExp('function ' + thisName + "(","g");//Create Reg Exp
   
    arrMatches
= fileContentAsStr.match(re);//Search the entire file content for the fnk name
 
}

I've tried:

re = new RegExp('function ' + thisName + "\(","g");//Same error


which produces the same error

and

re = new RegExp('function ' + thisName + "\\(","g");//No error but doesn't find anything


which doesn't cause an error but doesn't find anything

Alan Wells

unread,
Jan 14, 2020, 4:44:11 PM1/14/20
to Google Apps Script Community
If I use "search" instead of "match" with double escape it works.

--Hyde

unread,
Jan 14, 2020, 5:32:45 PM1/14/20
to Google Apps Script Community
Hi Alan,

The last variant you quote should work. Your regex will require the ( to be escaped, and JavaScript string literal handling will have turned \( into ( by the time it reaches RegExp, so you will have to double escape the string literal as in \\( to let RegExp see it as \(. Cannot say why the regex will not match function names in fileContentAsStr, but perhaps that is a white space or case-sensitivity issue. Try something like this:

var re = new RegExp('function\\s+' + thisName + '\\s*\\(''gi');

For regex testing, https://regex101.com/ is worth a visit — but keep in mind that the double escapes will have to be removed there.

Cheers --Hyde

Alan Wells

unread,
Jan 14, 2020, 6:28:18 PM1/14/20
to Google Apps Script Community
Thank you for the help.
That doesn't give me an error anymore, and most of the time it works.
I got a couple of unexpected results that I don't understand at all.  I'm trying something different with indexOf as a work around.

AD:AM

unread,
Jan 15, 2020, 2:30:04 PM1/15/20
to Google Apps Script Community
You may need to enable multiline processing, by including the m flag.
Reply all
Reply to author
Forward
0 new messages