testRegexSamples(pattern, samples) runs a regular expression against a list of sample strings and returns rows you can paste into a sheet: Sample, Match (yes/no), and any captured groups. Use it to see what a pattern actually does before you trust it on a column.
When to use
- Checking a validation regex against good and bad examples
- Explaining a pattern to a teammate with a visible yes/no table
- Debugging why a
MATCHor a form validator is too loose or too tight
How to use this snippet
/**
* Test a regex against samples. Returns a header plus one row per sample,
* ready for setValues: Sample, Match (yes/no), Captured (groups, comma-separated).
*
* @param {string|RegExp} pattern
* @param {Array} samples
* @return {Array<Array<string>>}
*/
function testRegexSamples(pattern, samples) {
var re;
try {
re = pattern instanceof RegExp ? new RegExp(pattern.source, pattern.flags) : new RegExp(String(pattern));
} catch (e) {
throw new Error('testRegexSamples: invalid pattern (' + e.message + ')');
}
var rows = [['Sample', 'Match', 'Captured']];
(samples || []).forEach(function (s) {
var text = s == null ? '' : String(s);
re.lastIndex = 0;
var m = re.exec(text);
re.lastIndex = 0;
if (m) {
rows.push([text, 'yes', m.slice(1).join(', ')]);
} else {
rows.push([text, 'no', '']);
}
});
return rows;
}
Example
function previewInvoicePattern() {
var rows = testRegexSamples('^INV-(\d+)$', [
'INV-12',
'inv-12',
'INV-99',
'INV-'
]);
SpreadsheetApp.getActive().getSheetByName('Regex tests')
.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
}
Notes
- A string pattern is compiled with
new RegExp(pattern)(no extra flags). Pass aRegExpif you neediorm. - Invalid patterns throw. An empty samples list returns just the header row.
- This does not change your data. Pair it with a Co-Pilot explanation of the pattern if you inherited the regex.
Happy Coding!
