1

I got text like: do[A]and[B]

I want to extract all words that are wrapped by [ and ].
I am using the match method:

var text = "do[A]and[B]";
var regexp = /\[(\w+)\]/g;
var result = text.match(regexp);

So I am saying that I want to match all words wrapped by [ ], but only the wrapped part should be in group/memory. I keep getting the [ ] parentheses in result:

["[A]", "[B]"]

expected result is:

["A","B"]

I thought this is a piece of cake to do, but I must be missing something.

Damb
  • 14,410
  • 6
  • 47
  • 49

2 Answers2

2

For this particular case you don't need capturing groups:

>>> "do[A]and[Bbbb]".match(/\w+(?=])/g);
["A", "Bbbb"]

will do.

1

In order to work with subpatterns, there is no easy shortcut.

Instead, you have to repeatedly execute the regex on the string and collect the subpattern you want. Something like this:

var text = "do[A]and[B]",
    regexp = /\[(\w+)\]/g,
    result = [], match;
while(match = regexp.exec(text)) {
    result.push(match[1]);
}
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592