Page 1 of 1

Need the the [^ab] thing, but for strings not characters

Posted: Thu Jan 17, 2008 11:12 pm
by dnmilne
Hi there,

I've been struggling with this seemingly simple regular expression problem. I'm hoping someone can show me how dumb I've been:

take the string {{aaa{{bbb}}ccc}}

What I need is a regex that would match the {{bbb}} part, but not the whole thing. Basically, anything in double brackets as long as it doesnt have nested stuff in double brackets within it.

The obvious solution is

m/\{{2}([^\{\}]*)\{{2}/

But the part I cant figure out is that the item matched should be allowed to contain single brackets.

eg: {{aaa{{b{bb}}ccc}} should match to "{{b{bb}}"

Basically, I need something like the [^ab] thing, but for strings ("{{" and "}}") rather than individual characters

Any suggestions?

Re: Need the the [^ab] thing, but for strings not characters

Posted: Thu Jan 17, 2008 11:52 pm
by Kieran Huggins
dnmilne wrote:The obvious solution is m/\{{2}([^\{\}]*)\{{2}/
First post, and already an awesome quote! :rofl:

I think what you want is called a "negative lookahead" (or lookbehind, as the case may be) - but you may want to get one of the more experienced regex guys to chime in.

Re: Need the the [^ab] thing, but for strings not characters

Posted: Fri Jan 18, 2008 1:55 am
by VladSun

Code: Select all

'/\{\{.+\{\{(.+)\}\}.+\}\}/'

Re: Need the the [^ab] thing, but for strings not characters

Posted: Thu Jan 24, 2008 4:08 am
by Chris Corbyn
VladSun wrote:

Code: Select all

'/\{\{.+\{\{(.+)\}\}.+\}\}/'
That would match what was first posted, except ~dnmilne needs to avoid the bit nested in the middle :) So just a slight modification:

Code: Select all

/\{\{(.(?!\{\{))*?\}\}/
This matches {{, followed by anything (except newlines) which *isn't followed by {{* any number of times, followed by }}.