Skip to content Skip to sidebar Skip to footer

JavaScript Regexp Repeating (sub)group

Is it possible to return all the repeating and matching subgroups from a single call with a regular expression? For example, I have a string like : {{token id=foo1 class=foo2 attr1

Solution 1:

This is impossible to do in one regular expression. JavaScript Regex will only return to you the last matched group which is exactly your problem. I had this seem issue a while back: Regex only capturing last instance of capture group in match. You can get this to work in .Net, but that's probably not what you need.

I'm sure you can figure out how to do this in a regular expressions, and the spit the arguments from the second group.

\{\{(\w+)\s+(.*?)\}\}

Here's some javaScript code to show you how it's done:

var input = $('#input').text();
var regex = /\{\{(\w+)\s*(.*?)\}\}/g;
var match;
var attribs;
var kvp;
var output = '';

while ((match = regex.exec(input)) != null) {
    output += match[1] += ': <br/>';

    if (match.length > 2) {
        attribs = match[2].split(/\s+/g);
        for (var i = 0; i < attribs.length; i++) {
            kvp = attribs[i].split(/\s*=\s*/);
            output += ' - ' + kvp[0] + ' = ' + kvp[1] + '<br/>';       
        }
    }
}
$('#output').html(output);

jsFiddle

A crazy idea would be to use a regex and replace to convert your code into json and then decode with JSON.parse. I know the following is a start to that idea.

/[\s\S]*?(?:\{\{(\w+)\s+(.*?)\}\}|$)/g.replace(input, doReplace);

function doReplace ($1, $2, $3) {
  if ($2) {
    return "'" + $2 + "': {" + 
      $3.replace(/\s+/g, ',')
        .replace(/=/g, ':')
        .replace(/(\w+)(?=:)/g, "'$1'") + '};\n';       
    }
   return '';
 }

REY


Solution 2:

You could do this:

var s = "{{token id=foo1 class=foo2 attr1=foo3 hi=we}} hiwe=wef";
var matches = s.match(/(\w+(?==\w+)|(?!==\w+)\w+)(?!\{\{)(?!.*token)(?=.*}})/g);
matches.splice(0,1);
for (var i = 0; i < matches.length; i++) {
    alert(matches[i]);
}

The regex is /(\w+(?==\w+)|(?!==\w+)\w+)(?!\{\{)(?!.*token)(?=.*}})/g (Use global modifier g to match all attributes)

The array will look like this:

["id","foo1","class","foo2","attr1","foo3","hi","we"]

Live demo: http://jsfiddle.net/HYW72/1/


Post a Comment for "JavaScript Regexp Repeating (sub)group"