修复 Sass / SCSS 括号缩进

发布于 2024-11-28 04:12:12 字数 806 浏览 1 评论 0原文

我为大家准备了一个正则表达式难题!

大约一周前,我决定将 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 的文本装饰之后添加另一行:我必须带上这两个括号。

无论如何,我一直在尝试找到完美的正则表达式来更改格式,但无济于事。

我的想法:

  1. 匹配并捕获 2 个空格,因为所有右括号都缩进至少一级: (\s{2})
  2. 匹配并捕获所有其他空格:(\s*) code>
  3. 匹配并捕获所有其他字符(我的 CSS 代码): (.*)
  4. 匹配空格 + 右括号: }

将其替换为两行: \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:

  1. Match and capture 2 spaces since all closing brackets are indented at least one level: (\s{2})
  2. Match and capture all additional spaces: (\s*)
  3. Match and capture all other characters (my CSS code): (.*)
  4. Match space + closing bracket: }

Replace that with two lines:
\1\2\3\n\2}

Doesn't exactly work quite yet. Appreciate any ideas.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

吖咩 2024-12-05 04:12:12

正如您所发现的,正则表达式实际上不起作用,因为含义/所需位置取决于对之前文档的解析。

您需要一个解析器或过滤器来完成这项工作。

幸运的是,有一个标准的 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. (^_^)

谜泪 2024-12-05 04:12:12

另一种简单的方法是在编辑器上进行快速替换,无需正则表达式,只需使其匹配空格,然后替换为新的括号/行。不过,可能不如使用 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文