1

I have many patterns with bracket enclosure, I made a regular expression where is not considering brackets and just only what is inside/between them, but exists a problem when the text within brackets contain [] brackets too.

Thanks!

Regex: (?<inside_value>(?<=\[).*?\[?(?=\]))

For example,

A)   [ClusterReceiver[99]            ]
B)   [first-second-third-8050-exec-a       ]

From above, B) is working perfectly, but A) not

What is being returned for every case (without quotes):

B) "first-second-third-8050-exec-a "
A) "ClusterReceiver[99"

What is desired?

B) "first-second-third-8050-exec-a "
A) "ClusterReceiver[99]"

The problem is when exist [ ] bracket enclosure within outer [ ] enclosure.

The worst case is when exists that problem like A), can you help me by giving a suggestion how to accept at least 1 bracket, in order to have A) as desired "ClusterReceiver[99]" ?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
dcubaz
  • 11
  • 2

1 Answers1

1

For those example strings, as the result with your pattern for B) is already working as you desired, if you want to accept at least 1 bracket you can optionally match an inner [...] part

(?<=\[)(?<inside_value>[^\][]*(?:\[[^\][]*][^\][]*)?)(?=])

Explanation

  • (?<=\[) Assert [ to the left
  • (?<inside_value> Start named group
    • [^\][]* Optionally match any char except [ or ]
    • (?: Non capture group
      • \[[^\][]*] Match [...]
      • [^\][]* Optionally match any char except [ or ]
    • )? Close the non capture group and make it optional
  • ) Close the named capture group
  • (?=]) Assert ] to the right

Regex demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70