1

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?

Knarf
  • 1,282
  • 3
  • 12
  • 31
  • http://stackoverflow.com/questions/3898210/greedy-non-greedy-all-greedy-matching-in-c-regex – N 1.1 Oct 20 '10 at 06:40

4 Answers4

4

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

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
1

Use a non-greedy match, ie

(\(.*?\))
Phil
  • 157,677
  • 23
  • 242
  • 245
0

If you don't care about nested parenthesis, use

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

to avoid matching any ( or ) inside a group.

kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0

How about

([^*]+)
Shaung
  • 508
  • 4
  • 11
  • 1
    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 Oct 20 '10 at 06:56