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

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
dnmilne
Forum Newbie
Posts: 1
Joined: Thu Jan 17, 2008 10:59 pm

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

Post 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?
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

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

Post 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.
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

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

Post by VladSun »

Code: Select all

'/\{\{.+\{\{(.+)\}\}.+\}\}/'
There are 10 types of people in this world, those who understand binary and those who don't
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

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

Post 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 }}.
Post Reply