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 03:58 AM
you can use string field type only
something like this will work
// Correct Format For RegEx should be like this -> ^[A-Z]{3}-\d{5}$
// Incorrect Format /^[A-Z]{3}-\d{5}$/
var toMatch = "someValue";
var myAnswer = false;
var gr = new GlideRecord('my_custom_table');
if (gr.get('xxxxxxxxx')) { // Replace with sys_id or query
var regexString = gr.getValue('u_regex_pattern');
// Handle empty regex case
if (!regexString) {
gs.error('No regex pattern found');
return;
}
try {
var pattern = new RegExp(regexString);
myAnswer = pattern.test(toMatch);
} catch (e) {
gs.error('Invalid regex: ' + regexString + ' | Error: ' + e.message);
}
gs.info('Match result for "' + toMatch + '": ' + myAnswer);
}
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-05-2025 04:59 AM
Let me check again.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-05-2025 07:24 AM
I tried few ways but seems it doesn't work i.e. dynamically use the regex stored in string filed
I will check this tomorrow and share updates.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-06-2025 03:02 AM
I tried this couple of times, but didn't work
The way how SNC.Regex and RegExp ServiceNow class works is different that native javascript so it's not considering the string as regex pattern
If my response helped please mark it correct and close the thread so that it benefits future readers.
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader