开发者

A (simple?) RegEx question for global non capturing groups

Say I have the string Hello {{name}}, how are you doing today? I'm trying to grab name from that string.

So far, I have /\{{2}[a-z0-9]*\}{2}/gi. The problem, is, it grabs {{name}} and not name. Without the global flag it works fine, but I'm trying to get every instance of words within double brackets, so it's not quite right... I'm no RegEx pr开发者_如何学JAVAo so I'm hoping someone can help me out...


The best solution would be to use lookaround assertions so the {{ and }} don't get picked up, however JavaScript regex doesn't support lookbehind, it only supports lookahead.

So one alternative is to place your text in a capture group and grab what's inside:

/\{{2}([a-z0-9]*)\}{2}/gi

To get every capture, make a RegExp object with your regex, and iterate through the results of its exec() function. For example:

var str = 'Hello {{name}}, how are you doing {{date}}?';
var re = /\{{2}([a-z0-9]*)\}{2}/gi;
var words = [];
var match;

while (match = re.exec(str)) {
    words.push(match[1]);
}

jsFiddle sample

Or as Gumbo suggests in his comment, manually strip out the {{ and }} from your array of matches.


Yea as mentioned, pattern matching on the 2 opening and closing braces is the way to go (assuming the name does not have curly braces in succession of the number of 2 within itself, either opening/closing)

/\{{2}([a-z0-9]+)*\}{2}/gi

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜