Efficient RegEx to Force Single Space After CSS At

2019-07-24 17:48发布

问题:

As I often work in Dreamweaver for basic CSS work ... DW code completion tends to add CSS attribute values directly after the colon without spacing ... {attr:value}. As this has caused some real debugging headaches due to rendering issues with picky browsers, I often find myself having to manually add the space after the colon. [^D.R.Y.]

I'm currently working on building a simple regex snippet that I can run to format the CSS properly ...

What I currently have seems to work but I think it's a bit crude ... I'm basically just trying to see if there are any suggestions ... Here's what I've got ...

(.*?(?={).*?:)([^\s][\w!#$%&'*+/=?^_`{|}~-]*.*?;}) 

And Replacing the line with ...

 \s$2 

► Clarification ► Below I've Somewhat Improved the Solution Above ... I Still Think It Needs Refinement Though ...

(?:(?={*))(?:\s*?)([\s\r\n]*?\b[\w!#$%&'*+/=?^_`|~-]*:(?!.*{))(?!\s)(.*?;) 

And Replacing With ...

$1 $2

► Perl Version ►

Perl makes very light work of this ...

perl -pi -e 's/^(.*?:)([^\s].*?;).*$/$1 $2/ig'

回答1:

If you run your regex snippet in a C# program, I have the solution for you:

Regex regex = new Regex(@"(?<=\{{1}[\s\r\n]*)((?<Attribute>[^}:\n\r\s]+):\s+(?<Value>[^;]*);[\s\r\n]*)*(?=\})");

regex.Replace(input, match =>
{
    var replacement = string.Empty;
    for (var i = 0; i < match.Groups["Attribute"].Captures.Count; i++)
    {
        replacement += string.Format(CultureInfo.InvariantCulture, "{0}: {1}\r\n", match.Groups["Attibute"].Captures[i], match.Groups["Value"].Captures[i]);
    }
    return replacement;
});


回答2:

If I understand you correctly, this should work (JavaScript)

'{attr:value}'.replace(/({.*?:)\s*/g,'$1 ')

This gives '{attr: value}' as the output.