如何根据空格数设置每行不同的颜色?

问题描述 投票:0回答:1

我想将一行中的文本颜色更改为红色,如果它有 4 个空格,如果有 8 个空格,则将其更改为蓝色,如果有 8 个空格,则将其更改为绿色,等等。我使用

.YAML
格式来实现此目的,但无论行开头有多少空格,文本始终设置为红色。

这些是我的尝试:

- match: ^\s{4}[\w\d_\.', ]*$
  scope: indent_1

- match: ^\s{8}[\w\d_\.', ]*$
  scope: indent_2

- match: ^\s{12}[\w\d_\.', ]*$
  scope: indent_3

显然,这段代码将整个文本设置为红色

text 1 (red)
    text 2 (red)
        text 3 (red)

第二次尝试,我使用捕获关键字组合了 2 个匹配项

- match: \s{4}[\w\d_\.', ]*$
  captures:
    1: indent_1
    2: indent_2
  push:
    - match: \s{4}, 
      scope: indent_1
    - match: $
      pop: true
  push:
    - match: \s{8}, 
      scope: indent_2
    - match: $
      pop: true

这会引发错误;

错误:加载语法文件“Packages/note/note.sublime-syntax”时出错:尝试解析 sublime-syntax 时出错::35:7 中的映射中存在重复键

另一次尝试,我在

OR(|)
表达式之间添加了
\s{n}
运算符,但此代码仅将其颜色设置为行开头的空格。

- match: (\s{4})|(\s{8})[\w\d_\.', ]*$
  captures:
    1: indent_1
    2: indent_2
  push:
    - match: \s{4}
      scope: indent_1
    - match: $
      pop: true
    - match: \s{8}
      scope: indent_2
    - match: $
      pop: true


    (color black) text 1
        (color black) text 2
            (color black) text 3

有什么办法可以解决这个问题吗?

regex yaml syntax-highlighting sublime-text-plugin sublimetext4
1个回答
2
投票

您正在使用此模式:

^\s{4}[\w\d_\.', ]*$

这里

\s
还可以匹配换行符,字符类
[\w\d_\.', ]
还可以匹配空格。

因此该模式至少匹配 4 个空白字符,但它也可以匹配其后面的空格,然后该模式将匹配所有情况。

请注意,

\w
也匹配
\d
_
,并且您不必在字符类中转义点
\.

可以使用

[^\S\r\n]
或例如
\h
(如果支持)来匹配没有换行符而不是单个空格的空白字符。那么您还可以匹配 8 个选项卡。

如果您想以 4 个空格开始匹配,并且后面的字符类中必须至少有一个字符不是空格:

^[ ]{4}[\w.',][\w.', ]*$

模式匹配:

  • ^
    字符串开头
  • [ ]{4}
    匹配 8 个空格(方括号仅为了清晰起见)
  • [\w.',]
    匹配单个单词字符或
    .
    '
    ,
  • [\w.', ]*
    匹配可选单词字符或
    .
    '
    ,
    或空格
  • $
    字符串结束

然后第二个模式将匹配 8 个空格等..

^[ ]{8}[\w.',][\w.', ]*$
© www.soinside.com 2019 - 2024. All rights reserved.