block by joyrexus ff7f5b26c38ff3784599

regex testing

Regex Testing

One way to deal with building and testing complex regular expressions is to break the overall pattern into component pieces, each of which can be tested individually.

Here’s one example of a complex pattern and it’s componentization:

'use strict';
var assert = require('assert');


// validation patterns for the `gsrel` column
function gsrelPatterns() {

    // pattern components
    var p = {
        code: {
            simple: 'DA|MS|UC|X|ADD|RF',
            add:    'ADD\\.(err|s|f|met|n[rs]|q|s)',
            rf:     'RF\\.[ap]'
        }
    };

    // pattern for all single codes
    p.single = [p.code.simple, p.code.add, p.code.rf].join('|');

    // pattern for all code combinations
    p.complex = '^(' + p.single + ')(([;\/])(' + p.single + '))*$';

    // final regex based on the complex pattern
    p.regex = new RegExp(p.complex);

    // method for testing whether values match final regex
    p.test = function(value) {
        return p.regex.test(value);
    };

    return p;
}

var gsrel = gsrelPatterns();


assert.equal(
    gsrel.single,
    'DA|MS|UC|X|ADD|RF|ADD\\.(err|s|f|met|n[rs]|q|s)|RF\\.[ap]'
);
assert.ok(gsrel.test('ADD.ns'));
assert.equal(gsrel.test('ADD.nx'), false);

regex.js