I have this string:
(3 + 5) * (1 + 1)
I want to match this strings:
(3 + 5)
and
(1 + 1)
I used this to try to match it:
(\(.*\))
But that matches the whole string, from the first ( to the last ).
Any idea on how to fix this / make it working?
,
There are two ways to look at this:
- Instead of greedy repetition
*
, I want reluctant*?
- i.e.
(\(.*?\))
- i.e.
- Instead of
.
, I want^)
, i.e. anything but)
- i.e.
(\(^)*\))
- i.e.
Note that neither handles nested parentheses well. Most regex engine would have a hard time handling arbitrarily nested parantheses, but in .NET you can use balancing groups definition.
Related questions
References
,
Use a non-greedy match, ie
(\(.*?\))
,
If you don’t care about nested parenthesis, use
(\(^()*\))
# ^^^^^
to avoid matching any (
or )
inside a group.
,
How about
(^*+)