views:

86

answers:

4

I have a regular expression to match anything between { and } in my string.

"/{.*}/"

Couldn't be simpler. The problem arises when I have a single line with multiple matches. So if I have a line like this:

this is my {string}, it doesn't {work} correctly

The regex will match

{string}, it doesn't {work}

rather than

{string}

How do I get it to just match the first result?

+3  A: 

Use a character class that includes everything except a right bracket:

/{[^}]+}/
Matt Kane
This is a better habit than the accepted answer. For a more complex regular expression, this will not fall prey to catastrophic backtracking. http://www.regular-expressions.info/catastrophic.html
Jeremy Stein
+6  A: 

Question-mark means "non-greedy"

"/{.*?}/"
David Hedlund
This is more readable, I think.
Matt Kane
i don't know if you'll aver have nested braces but this will not return desired results if they are there. for {aaa{bbb}ccc} it will return {aaa{bbb}.
Victor
This works as expected, although Victor's point is a good one. Possibly a topic for another post...
Travis
A: 

Default behaviour is greedy matching, i.e. first { to last }. Use lazy matching by the ? after your *.,

/{.*?}/

or even rather than * use "not a }"

/{[^}]*}/
cdm9002
+1  A: 

this will work with single nested braces with only a depth of one: {(({.*?})*|.*?)*}

I'm not sure how to get infinite depth or if it's even possible with regex

Victor