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,212
  • 3
  • 12
  • 29
  • 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
  • 364,035
  • 124
  • 554
  • 617
1

Use a non-greedy match, ie

(\(.*?\))
Phil
  • 141,914
  • 21
  • 225
  • 223
0

If you don't care about nested parenthesis, use

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

to avoid matching any ( or ) inside a group.

kennytm
  • 491,404
  • 99
  • 1,053
  • 989
0

How about

([^*]+)
Shaung
  • 498
  • 3
  • 10
  • 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