Reputation: 915
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
Reputation: 626689
You can use
[(\[][^()\[\]]*?text[^()\[\]]*[)\]]
Details:
[(\[]
- a(
or [
[^()\[\]]*?
- zero or more chars other than (
, )
, [
and ]
as few as possibletext
- a word text
[^()\[\]]*
- zero or more chars other than (
, )
, [
and ]
as many as possible[)\]]
- a )
or ]
char.See the regex demo.
Upvotes: 2
Reputation: 43441
Use two regex'es to match ()
or []
:
\[.*?text.*?\]|\(.*?text.*?\)
Upvotes: 0