Efficient RegEx to Force Single Space After CSS Attribute Value

ぃ、小莉子 提交于 2019-12-11 03:42:56

问题


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.



来源:https://stackoverflow.com/questions/7788319/efficient-regex-to-force-single-space-after-css-attribute-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!