1

Non-greedy regular expressions in Vim

2

For me its quite common that I want to substitute something in my buffer using a non-greedy regular expression. In VIM

3

this is done a little differently. Normally, I would use .? but that doesn't work in VIM.

4

5

Instead, you can use {-} instead of a to make VIM use a shortest match first algorithm.

6

7

As an example you can do this to unquote the keys in a JSON file:

8
:%s/\v"(.{-})"/\1
9

10

Here is an example of what that looks like in the package.json of this project:

11
non-greedy regular expression
Substitution using a non-greedy regular expression
12

13

This is something I find myself doing quite often. Whenever I work with a new API I usually curl that endpoint, pipe it

14

to jq for some nice formatting, and then redirect the output to a file. If I then choose to take a test driven approach,

15

and the response is dynamic enough to warrant tests for multiple variations, I might inline the fixtures as regular

16

javascript objects. I can then just copy that original JSON file and quickly execute a regex to unquote the keys.

16

17

The end

18

I usually tweet something when I've finished writing a new post. You can find me on Twitter

19

by clicking 

normalintroduction.md
||18:113

Recently Edited

Recently Edited

File name

Tags

Time to read

Created at

context

  • go
  • context
8 minutes2024-02-28

circular-buffers

  • go
  • concurrency
  • data processing
5 minutes2024-02-04

go-directives

  • go
  • compiler
  • performance
4 minutes2023-10-21

async-tree-traversals

  • node
  • trees
  • graphs
  • typescript
19 minutes2023-09-10

All Files

All Files

  • go

    5 files

  • node

    2 files

  • typescript

    1 file

  • frontend

    1 file

  • workflow

    7 files