4

I have a regex that matches everything inside brackets:

 ?\(.*?\)

I need adjust this regex, so it also matches nested brackets, for example:

ABC ( DEF (GHI) JKL ) MNO

Should match ( DEF (GHI) JKL ) in this example

Vnuuk
  • 6,177
  • 12
  • 40
  • 53
  • 4
    What are the *expected matches* in the example, please? – Dmitry Bychenko Jan 18 '18 at 13:59
  • Updated question – Vnuuk Jan 18 '18 at 14:00
  • 2
    Suppose we have an *elaborated example*: `ABC (DEF (GHI) JKL) MNO (PQR) (UV (XYZ)` what is the answer then? `{(DEF (GHI) JKL)`, `(PQR)}`, {`(DEF (GHI) JKL) MNO (PQR) (UV (XYZ)`}, or something else? – Dmitry Bychenko Jan 18 '18 at 14:05
  • Do you mean you need to *remove* all substrings inside nested brackets? [This solution](https://stackoverflow.com/a/19694656/3832970) should work actually. But there is another one: `while (Regex.IsMatch(s, @"\([^()]*\)")) { s = Regex.Replace(s, @"\([^()]*\)", ""); }` – Wiktor Stribiżew Jan 18 '18 at 19:26

2 Answers2

2

To match the ( DEF (GHI) JKL ) in ABC ( DEF (GHI) JKL ) MNO you should change .*? to .* in your example regex:

\(.*\)

.*? is lazy - it will match shortest possible string;

.* is greedy - it will match longest possible string.

Justinas Marozas
  • 2,482
  • 1
  • 17
  • 37
  • Your answer works perfect! Except one case - "This is ABC (XXX) DEF (XXX) (XXX)". For this string I expect to remove all (XXX) and have this - "This is ABC DEF". But regex also removed "DEF" for some reasons. – Vnuuk Jan 18 '18 at 14:15
1

If you want to match :

ABC ( DEF (GHI) JKL ) MNO

This works:

?\(.*\)

Ref: https://regex101.com/r/5Y5ZM0/2

EDIT: Updated with shorter working version from @GameDroids

Scath
  • 3,777
  • 10
  • 29
  • 40