dthree
dthree

Reputation: 20740

Regex - make this greedy

I have this regex pattern:

rxp = /\[!lang=([^}]+)\]/g

This looks at something like this:

[!lang=javascript]
var foo = 'bar';

And correctly returns ["javascript"]:

var found = [], rxp = /\[!lang=([^}]+)\]/g, curMatch;
while( curMatch = rxp.exec( myCodeStringAbove) ) {
  found.push( curMatch[1] );
}

// found === ['javascript']

BUT

If I have brackets later:

[!lang=javascript]
var foo = 'bar';
var fubar = [];

It freaks out and returns:

["javascript] var foo = 'bar'; var fubar = ["]

WHAT I NEED

I need to modify my regex pattern so that even though there are brackets later, it is greedy and stops at the first bracket, as in the first example above. How do I do this?

Upvotes: 0

Views: 105

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

there is an error in your character class. You forbbid a closing curly bracket instead of a square curly bracket:

rxp = /\[!lang=([^\]]+)]/g

Upvotes: 2

jkshah
jkshah

Reputation: 11703

One way is to force greedy operator + to be lazy by adding ? after it

/\[!lang=(.+?)\]/g

regex101 demo

Upvotes: 1

Related Questions