Match single character not enclosed by braces

146 views Asked by At

I am making a property list syntax definition file (tmLanguage) for practice. It's in Sublime Text's YAML format, but I'll be using it in VS Code.

I need to match all characters (including unterminated { and }) that are not enclosed by {}.

I have tried using negative lookahead and lookbehind assertions, but it just matches not the first or last character in brackets.

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

Adding a greedy quantifier to consume all characters just matches the full line.

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

Adding a lazy quantifier just matches everything except the first character after the {. It also matches {} exactly.

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

| 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` `}` |
| `{}`              | `{` `}`                 |

Sample text file: https://raw.githubusercontent.com/spikespaz/windows-tiledwm/master/hotkeys.conf


Full syntax highligher:

# [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: \#.*
...
1

There are 1 answers

0
Poul Bak On

You can use the following RegEx to match:

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

Then simply replace the matches with an empty string and what you get is according to your wishes.

The RegEx is selfexplaining, but here's a short description:

It creates a non capturing Group consisting of one of your modifier keys in curly brackets. The plus sign '+' at the right means it repeats that one or more times.