php - preg_match_all to javascript -
can converting php regex pattern javascript compatible one?
php
preg_match_all('/(?ims)([a-z0-9\s\.\:#_\-@,]+)\{([^\}]*)\}/', $data, $matches);
javascript
matches=data.match(/(?ims)([a-z0-9\s\.\:#_\-@,]+)\{([^\}]*)\}/);
thanks
to mimic php output, need @ more regular expression. single match, javascript match method trick, multiple matches no longer return captured groups. in fact, there no out-of-the-box statement in javascript equivalent preg_match_all.
the method comes closest regex.exec, being method can both return captured groups , multiple matches. not return matches in 1 go. instead need iterate on them, instance this:
for (matches = []; result = regex.exec(data); matches.push(result));
now regular expression needs adjustments:
in javascript modifiers (ims) cannot specified have it, must specified @ end, after closing slash. note in php can same.
secondly, javascript has no support s modifier. in case not problem, regular expression not rely on -- same results without modifier.
in order exec method return multiple matches, regular expression must use g modifier, not needed nor allowed in php's preg_match_all -- _all in method name takes care of that.
so, in javascript, regular expression defined this:
var regex = /([a-z0-9\s\.\:#_\-@,]+)\{([^\}]*)\}/gim;
finally, matches returned in different format in php. let's data "alpha{78} beta{333}", php return:
[["alpha{78}"," beta{333}"],["alpha"," beta"],["78","333"]]
but above javascript code returns data in transposed way (rows , columns swapped):
[["alpha{78}","alpha","78"],[" beta{333}"," beta","333"]]
so, if want same, need transpose array. here generic transpose function use that:
function transpose(a) { return a[0].map(function (val, c) { return a.map(function (r) { return r[c]; }); }); }
so putting together, job:
function transpose(a) { return a[0].map(function (val, c) { return a.map(function (r) { return r[c]; }); }); } // test data: var data = "alpha{78} beta{333}"; var regex = /([a-z0-9\s\.\:#_\-@,]+)\{([^\}]*)\}/gim; // collect matches in array (var matches = []; result = regex.exec(data); matches.push(result)); // reorganise array mimic php output: matches = transpose(matches); console.log(json.stringify(matches)); // snippet only: document.write(json.stringify(matches));
output:
[["alpha{78}"," beta{333}"],["alpha"," beta"],["78","333"]]
Comments
Post a Comment