regexp-utils
Advanced tools
Comparing version 0.1.1 to 0.2.0
37
index.js
@@ -45,2 +45,12 @@ "use strict"; | ||
/** | ||
* Determine how many capturing groups a regexp contains | ||
*/ | ||
RU.countCapturingGroups = function numberOfGroups (re) { | ||
// Construct a regexp that always matches | ||
var testRe = new RegExp('|' + re); | ||
// And use the length of the result to determine the number of groups | ||
return ''.match(testRe).length - 1; | ||
}; | ||
/** | ||
* Build a regexp-based switch | ||
@@ -66,17 +76,22 @@ * | ||
values = {}, | ||
reOffset = 0, | ||
reBit; | ||
for (var i = 0, l = regexps.length; i < l; i++ ) { | ||
var re = regexps[i]; | ||
regexps.forEach(function(re) { | ||
if (Array.isArray(re)) { | ||
values[i] = re[1]; | ||
values[reOffset] = re[1]; | ||
re = re[0]; | ||
} | ||
if (RU.isRegExp(re)) { | ||
matchers[i] = re; | ||
reBit = RU.makeGroupsNonCapturing(RU.toSource(re)); | ||
reBit = RU.toSource(re); | ||
if (re.length === undefined) { | ||
re.length = RU.countCapturingGroups(reBit); | ||
} | ||
matchers[reOffset] = re; | ||
reOffset += re.length + 1; | ||
} else { | ||
reBit = RU.escapeRegExp(re); | ||
reOffset++; | ||
} | ||
reBits.push('(' + reBit + ')'); | ||
} | ||
}); | ||
var switchRe = new RegExp(reBits.join('|')); | ||
@@ -86,3 +101,4 @@ return function regExpSwitcher (s) { | ||
if (match) { | ||
for (var i = 1, l = match.length; i < l; i++) { | ||
var i = 1, l = match.length; | ||
for (; i < l; i++) { | ||
if (match[i]) { | ||
@@ -93,4 +109,7 @@ break; | ||
if (matchers[i-1]) { | ||
// re-run the actual regexp with capturing groups | ||
match = s.match(matchers[i-1]); | ||
// extract the capturing group results | ||
var newMatch = match.slice(i, i + matchers[i-1].length + 1); | ||
newMatch.index = match.index; | ||
newMatch.input = s; | ||
match = newMatch; | ||
} else { | ||
@@ -97,0 +116,0 @@ match = [match[0], match[i]]; |
{ | ||
"name": "regexp-utils", | ||
"version": "0.1.1", | ||
"version": "0.2.0", | ||
"description": "RegExp related utilities", | ||
@@ -5,0 +5,0 @@ "main": "index.js", |
10
test.js
@@ -6,3 +6,3 @@ // TODO: Set up real tests | ||
var switcher = RU.makeRegExpSwitch([ | ||
/arsta(sat((sarsdta)))/, | ||
[/arsta(sat((sarsdta)))/, 'Lots of nesting'], | ||
'arsda()arstao[3424]', | ||
@@ -15,4 +15,4 @@ [/fo(o)/, 'foo matched!'], | ||
if (JSON.stringify(a) !== JSON.stringify(b)) { | ||
console.error('FAILURE: Expected' , JSON.stringify(a), | ||
', saw', JSON.stringify(b)); | ||
console.error('FAILURE: Expected' , JSON.stringify(b), | ||
', saw', JSON.stringify(a)); | ||
process.exit(1); | ||
@@ -22,2 +22,6 @@ } | ||
assert( switcher('arstasatsarsdta'), | ||
{ match: ['arstasatsarsdta', 'satsarsdta', 'sarsdta','sarsdta'], | ||
value: 'Lots of nesting' } ); | ||
assert( switcher('foo'), | ||
@@ -24,0 +28,0 @@ { match: ['foo', 'o'], |
5338
144