Knarf
Knarf

Reputation: 1273

Regex problem, matches the whole string instead of a part

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?

Upvotes: 1

Views: 378

Answers (4)

polygenelubricants
polygenelubricants

Reputation: 383726

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

Upvotes: 4

Shaung
Shaung

Reputation: 508

How about

([^*]+)

Upvotes: 0

kennytm
kennytm

Reputation: 523224

If you don't care about nested parenthesis, use

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

to avoid matching any ( or ) inside a group.

Upvotes: 0

Phil
Phil

Reputation: 164762

Use a non-greedy match, ie

(\(.*?\))

Upvotes: 1

Related Questions