kevinharalson
Mega Expert

ServiceNow employs the ES5 (2009) version of rhino javascript. As a result, RegEx Lookbehind Assertions introduced in 2018 as part of the ECMAScript language specification, per https://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent, will receive a script error.

A new OOB "Variable Validation Regex" expression containing a Lookbehind Assertion has been introduced for validation of email addresses, and use of this expression within a script running the ES5 version of javascript will result in a script error.  

Fix Script using ES5 version of rhino javascript and RegEx Lookbehind Assertion

var expName = 'email';
var input = 'someone@corp.somewhere.net';

var regexpressions = new GlideRecord('question_regex');
regexpressions.addQuery('name',expName);
regexpressions.addActiveQuery();
regexpressions.query();
while (regexpressions.next()) {
    var exprString = regexpressions.regex.toString();
    gs.print('RegExp using ' + exprString);
    var exp = new RegExp(exprString);
    if (!exp.test(input)){
        gs.print('Invalid Input('+ input +')');
    }
    else {
        gs.print('Valid Input('+ input +')');
    }
}

Error Received

Workaround using Java to test RegEx Lookbehind Assertion

Per https://docs.servicenow.com/bundle/rome-application-development/page/script/general-scripting/concept/c_RegularExpressionsInScripts.html, the "j" extended regular expression flag can be used to define a regular expression that executes using the Java regular expression engine.

var expName = 'email';
var input = 'someone@corp.somewhere.net';

var regexpressions = new GlideRecord('question_regex');
regexpressions.addQuery('name',expName);
regexpressions.addActiveQuery();
regexpressions.query();
while (regexpressions.next()) {
    var exprString = regexpressions.regex.toString();
    gs.print('RegExp using ' + exprString);
    var exp = new RegExp(exprString,'j');
    if (!exp.test(input)){
        gs.print('Invalid Input('+ input +')');
    }
    else {
        gs.print('Valid Input('+ input +')');
    }
}

Comments
Andy Hopper
Tera Contributor

This really helped to get me out of a jam: I could NOT figure out why my lookahead/lookbehind expression wasn't working!  So, thanks!

In case it helps someone in future: if you're creating expressions on-the-fly (i.e. from runtime variables; not looking them up from a regex table, as shown in the original post) then you need to make sure you escape every backslash '\' character for tokens in your expression by doubling it up '\\' otherwise the RegExp() method will strip it and escape the next character afterwards.

For example a whitespace token of \s needs to become \\s otherwise RegExp() will interpret it simply as s

 

ldave
Giga Guru

Super useful, thanks to both! I was getting crazy. The double \\ information is super important too.

Version history
Last update:
‎09-13-2021 09:14 AM
Updated by: