Reputation: 2492
I'm using this expression:
"g{field1}={field2}a".match(/{([^\{\}]+)\}/g)
What I need is to get "field1" and "field2", but it returns an array with "{field1}" and "{field2}".
Upvotes: 2
Views: 428
Reputation: 147363
You can also do:
'g{field1}={field2}a'.split(/[{}]/).filter(function(a,i){return i%2;});
provided the string always contains matching "{}" pairs. There is also:
'g{field1}={field2}a'.split(/^[^{]*\{|\}[^{]*\{|\}[^{]*$/g).slice(1,-1);
both of which will work on any number of {…} pairs (0 to n).
Upvotes: 0
Reputation: 13615
You could use a lookahead
"g{field1}={field2}a".match(/[^\{\}]+(?=\})/g)
this will match any character that is not {
or }
if the matched set of characters is followed by a }
Upvotes: 1
Reputation: 43718
You can use exec
which can return multiple capturing groups per matches.
var re = /{([^\{\}]+)\}/g,
matches = [],
input = "g{field1}={field2}a",
match;
while (match = re.exec(input)) matches.push(match[1]);
console.log(matches);
You can also re-write your regex (here it depends what the input string can be):
var matches = "g{field1}={field2}a".match(/{([^}]+)}={([^}]+)}/).slice(1);
console.log(matches);
Upvotes: 3
Reputation: 11258
"g{field1}={field2}a".match(/([^g=a\{\}]+)/g)
returns
["field1", "field2"]
Upvotes: 0
Reputation: 944
If you just want an array without curly braces, you can use array map method:
"g{field1}={field2}a".match(/{([^\{\}]+)\}/g).map(function(i){return i.slice(1,-1)})
Upvotes: 2