Is it possible to store regex in a field and then use it in code?

Nisar3
Giga Guru

I've a custom table in which I can create a new field. The purpose of this field will be to store regex expression.

 

Then in the code I wish to use the following:

var toMatch = "someValue";
var myAnswer = false;
var gr = new GlideRecord('my_custom_table');
if(gr.get('xxxxxxxxx'))
{
     var pattern = new RegExp(gr.getValue('regex_column_name'));
     if(pattern.test(toMatch)){
         myAnswer = true;
     }

     gs.info('myAnswer ' + myAnswer);
}



I tried setting the field type to "String" but that doesn't seem to work. Is there a specific "column type" that I can try?

10 REPLIES 10

Abhijit4
Mega Sage

Hi @Nisar3 

 

As your regex pattern would be dynamic based on field value. So, you could use below syntax to validate

 

`${word}`
 
Your updated script ( I have tested this with incident table and incident field and it works perfectly so it should work with your custom table as well):
var toMatch = "someValue";
var myAnswer = false;
var gr = new GlideRecord('my_custom_table');
if(gr.get('xxxxxxxxx'))
{
var jsonPattern=gr.getValue('regex_column_name');
     var pattern = new RegExp(`${jsonPattern}`);
     if(pattern.test(toMatch)){
         myAnswer = true;
     }

     gs.info('myAnswer ' + myAnswer);
}

 

If my response helped please mark it as correct.

 

Regards,

Abhijit 

ServiceNow MVP

ServiceNow Buddy Owner: snbuddy.com

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP

Interesting, what's the significance of "$"?

 

Because in Ankur's post, it is not used

var pattern = new RegExp(regexString);

v/s

var pattern = new RegExp(`${regexString}`);

@Nisar3 

 

This Syntax ( ${word} ) is specifically designed to handle dynamic regex validation.

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP

Tried your approach via background script. Seems like it's throwing syntax error for using "`"

Nisar3_0-1746521051057.png

 

@Nisar3  It is ServiceNow global parser that highlights error. You can ignore it and run script, it will work.

 

You may not see it if you try with fix script.

 

 

By marking my response as correct or helpful, you contribute to helping future readers with similar issues.
Regards,
Abhijit
ServiceNow MVP