修复 Sass / SCSS 括号缩进
我为大家准备了一个正则表达式难题!
大约一周前,我决定将 Sass 文件的格式从以下更改为:
a {
color: red;
text-decoration: none;
&:hover: {
color: blue;
text-decoration: underline;
}
}
div { ... }
第二种
a {
color: red;
text-decoration: none;
&:hover: {
color: blue;
text-decoration: underline; } }
div { ... }
语法看起来不错——它可以节省行数并提高可读性——但这实际上对于编写代码来说是一场灾难。想象一下,如果我想在 a:hover 的文本装饰之后添加另一行:我必须带上这两个括号。
无论如何,我一直在尝试找到完美的正则表达式来更改格式,但无济于事。
我的想法:
- 匹配并捕获 2 个空格,因为所有右括号都缩进至少一级:
(\s{2})
- 匹配并捕获所有其他空格:
(\s*)
code> - 匹配并捕获所有其他字符(我的 CSS 代码):
(.*)
- 匹配空格 + 右括号:
}
将其替换为两行: \1\2\3\n\2}
还不能完全正常工作。欣赏任何想法。
I have a regex puzzle for you all!
A week or so ago, I decided to change the formatting of my Sass file from this:
a {
color: red;
text-decoration: none;
&:hover: {
color: blue;
text-decoration: underline;
}
}
div { ... }
To this:
a {
color: red;
text-decoration: none;
&:hover: {
color: blue;
text-decoration: underline; } }
div { ... }
The second syntax seems nice -- it saves you lines and improves readability -- but it is actually a disaster for writing code. Imagine if I wanted to add another line after a:hover's text-decoration: I'd have to bring those two parentheses with me.
Anyway, I've been trying to find the perfect regex to change the formatting back but to no avail.
My thinking:
- Match and capture 2 spaces since all closing brackets are indented at least one level:
(\s{2})
- Match and capture all additional spaces:
(\s*)
- Match and capture all other characters (my CSS code):
(.*)
- Match space + closing bracket:
}
Replace that with two lines:\1\2\3\n\2}
Doesn't exactly work quite yet. Appreciate any ideas.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您所发现的,正则表达式实际上不起作用,因为含义/所需位置取决于对之前文档的解析。
您需要一个解析器或过滤器来完成这项工作。
幸运的是,有一个标准的 JS 美化器,或者一个 CSS 压痕 应该将该文件恢复原状。
PS:还要考虑更频繁的备份和版本控制。 (^_^)
Regex won't really work, as you've discovered, because the meaning/desired position depends on the parsing of the Document that has come before.
You need a parser or a filter for this job.
Fortunately, a standard JS beautifier, or a CSS indenter should whip that file right back into shape.
PS: Also consider more frequent backups and version control. (^_^)
另一种简单的方法是在编辑器上进行快速替换,无需正则表达式,只需使其匹配空格,然后替换为新的括号/行。不过,可能不如使用 css 重新缩进器那么快。
Another easy way to do it is to do a quick replace on your editor, no regex, just make it match the spaces, replace with the new brackets/lines. Might not be as quick as using a css re-indenter though.