dcubaz
dcubaz

Reputation: 11

Is possible to discard outer brackets in regex and consider inner bracket inside?

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]" ?

Upvotes: 1

Views: 42

Answers (1)

The fourth bird
The fourth bird

Reputation: 163207

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

Upvotes: 1

Related Questions