[SOLVED] Regex group does not catch brackets


This Content is from Stack Overflow. Question asked by Filip Tonic

I have following regex: ‘Word:((?< term >)[a-zA-Z()]*)’ -> JS

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?


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)
let m;

while ((m = regex.exec(str)) !== null) {

This Question was asked in StackOverflow by FilipT and Answered by The fourth bird It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?