Regex group does not catch brackets

Viewed 35

I have following regex:

Word:(\(?<term>\)[a-zA-Z()]*)

If I pass (Word:Arm) it will capture Arm, but if I want to pass (Word:(Arm)) it does not match a thing. I need this second case to capture (Arm), brackets included.

How can I achieve this?

1 Answers

If you don't want to match the parenthesis at all, you can exclude them in the character class.

To match the balanced parentheses, instead of making one optional you can use an alternation matching with or without parenthesis.

Using a case insensitive pattern with /i

const regex = /Word:(?<Term>\([a-z]+\)|[a-z]+)/i;

Regex demo

const regex = /Word:(?<Term>\([a-z]+\)|[a-z]+)/gmi;
const str = `(Word:Arm)
(Word:(Arm))`;
let m;

while ((m = regex.exec(str)) !== null) {
  console.log(m.groups["Term"]);
}

Related