hoshiKuzu
hoshiKuzu

Reputation: 915

How to match the closest opening and closing brackets

I have the regex [(\[].*?text.*?[)\]]

I intend to match everything inside the bracket containing "text", including the brackets themselves, but not other sibling brackets. The brackets will not be nested.

With the text: [filler dontmatch filler] ( filler text filler)

[filler dontmatch filler] also gets matched.

However, ( filler text filler) [filler dontmatch filler] works as intended.

Something about regex working from left to right?

How do I make it work in both cases? I am using the java regex engine.

Edit: I don't care about balancing the same type of brackets, but the text and the closest brackets enclosing it should be matched.

Upvotes: 1

Views: 2403

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can use

[(\[][^()\[\]]*?text[^()\[\]]*[)\]]

Details:

  • [(\[] - a( or [
  • [^()\[\]]*? - zero or more chars other than (, ), [ and ] as few as possible
  • text - a word text
  • [^()\[\]]* - zero or more chars other than (, ), [ and ] as many as possible
  • [)\]] - a ) or ] char.

See the regex demo.

Upvotes: 2

Justinas
Justinas

Reputation: 43441

Use two regex'es to match () or []:

\[.*?text.*?\]|\(.*?text.*?\)

Regex101 example

Upvotes: 0

Related Questions