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

Ankur Bawiskar
Tera Patron
Tera Patron

@Nisar3 

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.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Let me check again.

@Nisar3 

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.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Nisar3 

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.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader