Is it possible to store regex in a field and then use it in code?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-02-2025 03:43 AM
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-02-2025 04:11 AM - edited 05-02-2025 04:12 AM
Hi @Nisar3
As your regex pattern would be dynamic based on field value. So, you could use below syntax to validate
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
Regards,
Abhijit
ServiceNow MVP
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-05-2025 05:00 AM
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}`);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-05-2025 06:01 AM
This Syntax ( ${word} ) is specifically designed to handle dynamic regex validation.
Regards,
Abhijit
ServiceNow MVP
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-06-2025 01:44 AM
Tried your approach via background script. Seems like it's throwing syntax error for using "`"
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-06-2025 02:08 AM
@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.
Regards,
Abhijit
ServiceNow MVP