开发者

Regex: Match White Space & New Lines Until Specific Character

I'm trying to write a macro for Textmate to take a few lines of code and turn them into one css line. So:

#rules #footer ul { margin: 0 auto;
text-align: colorenter;
width: 700px;}

would become

#rules #footer ul { margin: 0 auto;text-align: colorenter;width: 700px;}

so basically I need to match new lines and white space and turn them into just a single space UNTIL it hits } that's where it ends. I don't want to go over the entire css file just the one block.

I'm really ba开发者_JAVA百科d at regex any help would be GREATLY appreciated...


Look for the pattern:

\s+(?=[^{}]*})

and replace it with a single space.

\s+ matches one or more white space characters (space, tab, line-break) only when looking ahead a } can be seen without encountering a { between it.

Beware that this will go wrong in cases like this:

#rules #footer ul { margin: 0 auto;
text-align: colorenter;              /*    }     */
width: 700px;}

A little PHP demo:

<?php
$css = '#rules #footer ul { margin: 0 auto;



text-align: colorenter;



width: 700px;}

#rules #footer ul { margin: 0 auto;
text-align: colorenter;
width: 700px;}';

echo preg_replace('/\s+(?=[^{}]*})/', ' ', $css);
?>

will print:

#rules #footer ul { margin: 0 auto; text-align: colorenter; width: 700px;}

#rules #footer ul { margin: 0 auto; text-align: colorenter; width: 700px;}

as you can see on Ideone.


If your tool supports later versions of PCRE or the like, and you want this to remove line breaks from selectors as well, then you could use a regex like

(?:\S(?<!})|^)[ \t]*\K[\n\r]\s* replaced by a space.

I wrote this to only remove line breaks and white space at the beginning of lines. You could use an equivalent of s/(\s)\s+/$1/g to remove all double spaces in other places too.

Perl demo:

perl -E "$_=qq'foo,\noof {\n\tbar /* } */\n\tbaz\n}\nfoo{\nbaz\n}';say;s/(?:\S(?<!})|^)[ \t]*\K[\n\r]\s*/ /g;say"

Input:

foo,
oof {
        bar /* } */
        baz
}
foo{
baz
}

Result:

foo, oof { bar /* } */ baz }
foo{ baz }


There's actually a much simpler solution. Just make a macro that replaces newlines with spaces. You'd have to only run it on selections, but I think that's all you wanted in the first place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜