tags:

views:

71

answers:

2

Hi, Assuming I've been given the following string to match against:

#sidebar h1 ul li{ #a:hover; height : 100px ;color: #fffff ; font-family: @fonts; }

What I want is to only match whitespaces within the curly braces { } that are not enclosed on both sides by words.

My current regex looks like this:

( (?!\w)|(?<!\w) )

But it matches characters outside the braces too. I tried look-around, but it's not really working out the way I imagined it and I just suck at regex..

I want to strip all whitespaces from css classes content so the string would be condensed to:

#sidebar h1 ul li{#a:hover;height:100px;color:#fffff;font-family:@fonts;}

Btw, I'm using the .NET Regex engine, so if anyone needs a quick testing environment for that, I found this Silverlight one pretty handy: http://www.regexlib.com/RESilverlight.aspx

+1  A: 

Try this:

Regex.Replace(str, @"(?:\B\s+|\s+\B)(?=[^{}]*\})", "")

But this can be fooled if there are rules inside @media sections (ie, nested braces), or voice rules that use braces as metacharacters.

Alan Moore
Thanks. This appears to work, but since I also want to support @media sections I'll have to look into a solution without regex
Tigraine
+2  A: 

Given that some CSS elements have multi-word values (border: 1px solid red) the whitespace removal process you describe would be disastrous. I would recommend that you just remove whitespace in the following places:

  • After '{'
  • Before '}'
  • Before and after ';'
  • Before and after ':'

Luckily, because of the syntax of CSS, none of these patterns will occur outside the {...} sections. Unfortunately, I do not know the specifics of .NET regex engine, maybe this will work:

( +(?=[};:])|(?<=[{;:]) +)
too much php