Nigiri
Nigiri

Reputation: 3639

Different between /{.*?}/g. and /{(.*?)}/g

In Chrome,

/{.*?}/g.exec('aaa{eee}uuuu')

returns

["{eee}"]

, whereas

/{(.*?)}/g.exec('aaa{eee}uuuu')

returns

["{eee}", "eee"]

The second result is what I expected. Why not the first code return the naked string of "{eee}"?

Upvotes: 0

Views: 153

Answers (1)

Vegeta
Vegeta

Reputation: 1317

Because in first regex you did not used braces. braces is used to group the string passed but in second regex you have used braces which group "eee" according to your input.

First regex returns array with only one element that matches. but in second expression it return array with 2 element . [0] => whole string matched, [1] => string matched inside braces. If more braces are used then it will return [2] => ...,[3] => ... , etc

refer: JavaScript Regex Global Match Groups

Upvotes: 1

Related Questions