0

I'm trying to figure out a problem I'm having with regex.

I'm using this regex with preg_match_all on a large multi line string:

 /(\{(if|while|function|loop|\$|#)(.+)\})/

It currently works to match all text that starts with { and ends with } such as {$test} or {$function="test()"}

However, if one line in the string contains two matching blocks, the regex returns the whole line such as:

{$value.url}" class="link">{$value.title}

I can't figure out how to make the regex not do a 'greedy' match with (.+). The reason why I have (.+) is because there could be any character/number/underscore/period/quote/space in between the two brackets {}.

Can someone help me out?

2
  • Is this also validating or supporting nesting, what should happen if the string was {if {$fish} do } Commented Jul 29, 2011 at 11:29
  • That is a good question, however we are using a templating engine that doesn't use nested {}, your example would be {if="$fish"}This is a {$fish}{/if}. We just needed a quick request to scan all our files to find out which files had the if/while/etc statements in them. Commented Jul 29, 2011 at 11:48

2 Answers 2

1

You can make the .+ ungreedy by adding a question mark like this .+?

Sign up to request clarification or add additional context in comments.

Comments

1

Try matching for everything except for the } and then the }.

/(\{(if|while|function|loop|\$|#)([^\}]+)\})/

3 Comments

That would break nesting (eg. {if {fish} do} would return {if {fish}
I think any non-greedy match will break nesting. I would have to imagine at that point that simple regex wouldn't cut it and it would move into full token parser type stuff. But I could be wrong.
True, but you could require no open brace instead so [^\{\}] which would then at least match a balanced pair on the inner nest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.