【问题标题】:Match single character not enclosed by braces匹配不被大括号括起来的单个字符
【发布时间】:2026-01-20 09:50:01
【问题描述】:

我正在制作一个属性列表语法定义文件 (tmLanguage) 以供练习。它是 Sublime Text 的 YAML 格式,但我将在 VS Code 中使用它。

我需要匹配所有未被{} 包围的字符(包括未终止的{})。

我尝试过使用否定的前瞻和后瞻断言,但它不匹配括号中的第一个或最后一个字符。

(?<!{).(?!})

添加一个贪心量词来消耗所有字符正好匹配整行。

(?<!{).+(?!})

添加惰性量词只会匹配除{ 之后的第一个字符之外的所有内容。它也完全匹配{}

(?<!{).+?(?!})

| Test              | Expected Matches        |
| ----------------- | ----------------------- |
| `{Ctrl}{Shift}D`  | `D`                     |
| `D{Ctrl}{Shift}`  | `D`                     |
| `{Ctrl}D{Shift}`  | `D`                     |
| `{Ctrl}{Shift}D{` | `D` `{`                 |
| `{Ctrl}{Shift}D}` | `D` `}`                 |
| `D}{Ctrl}{Shift}` | `D` `}`                 |
| `D{{Ctrl}{Shift}` | `D` `{`                 |
| `{Shift`          | `{` `S` `h` `i` `f` `t` |
| `Shift}`          | `S` `h` `i` `f` `t` `}` |
| `{}`              | `{` `}`                 |

示例文本文件:https://raw.githubusercontent.com/spikespaz/windows-tiledwm/master/hotkeys.conf


完整语法高亮:

# [PackageDev] target_format: plist, ext: tmLanguage
---
name: Hotkeys Config
scopeName: source.hks
fileTypes: ["hks", "conf"]
uuid: c4bcacab-0067-43db-a1d7-7a74fffe2989

patterns:
- name: keyword.operator.assignment
  match: \=
- name: constant.language
  match: "null"
- name: constant.numeric.integer
  match: \{(?:Alt|Ctrl|Shift|Super)\}
- name: constant.numeric.float
  match: \{(?:Menu|RMenu|LMenu|Tab|Enter|PgUp|PgDown|Ins|Del|Home|End|PrntScr|Esc|Back|Space|F[0-12]|Up|Down|Left|Right)\}
- name: comment.line
  match: \#.*
...

【问题讨论】:

  • {{{{}}{ } 的预期结果是什么?在{{} 中应该匹配哪个左大括号?

标签: regex syntax tmlanguage


【解决方案1】:

您可以使用以下RegEx进行匹配:

(?:{(Ctrl|Shift|Alt)})*

然后只需将匹配项替换为空字符串,得到的就是你想要的。

RegEx 不言自明,但这里有一个简短的描述:

它会创建一个non capturing Group,由花括号中的一个修饰键组成。右侧的加号“+”表示它重复了一次或多次。

【讨论】:

    最近更新 更多