tags:

views:

41

answers:

4

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?

+1  A: 

Use a non-greedy match, ie

(\(.*?\))
Phil Brown
A: 

If you don't care about nested parenthesis, use

(\([^()]*\))
#  ^^^^^

to avoid matching any ( or ) inside a group.

KennyTM
A: 

How about

([^*]+)
Shaung
A bit too specific to the example -- it won't work in more general cases, where the thing separating the groups of parentheses might not be `*`.
cHao
+3  A: 

There are two ways to look at this:

  • Instead of greedy repetition *, I want reluctant *?
    • i.e. (\(.*?\))
  • Instead of ., I want [^)], i.e. anything but )
    • 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

polygenelubricants