Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

regex - 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=foo3}}

Where the number of attributes (i.e. id, class, attr1) are undefined and could be any key=value pair.

For example, at the moement, I have the following regexp and output

var pattern = /{{([w.]+)(?:s+(w+)=(?:("(?:[^"]*)")|([w.]+)))*}}/;
var str = '{{token arg=1 id=2 class=3}}';

var matches = str.match(pattern);
// -> ["{{token arg=1 id=2 class=3}}", "token", "class", undefined, "3"]

It seems that it only matches the last group; Is there any way to get all the other "attributes" (arg and id)?

Note: the example illustrate match on a single string, but the searched pattern be be located in a much larger string, possibly containing many matches. So, ^ and $ cannot be used.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

/[sS]*?(?:{{(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'") + '};
';       
    }
   return '';
 }

REY


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...