Double your indentation with regular expressions!

Say you have a code sample where each level of indentation is indented by only one space more than the previous level:

 "version": "1.0",
 "superitem": {
  "item": {
   "subitem": {
    "data": "test"

Say you want to change the indentation to be two spaces per level.

And say you want to do this using the regular-expression search-and-replace tool in a text editor, like BBEdit.

How would you go about it?

There may be some cleverer way to do it, but I was reasonably pleased with the semi-kludgy approach I came up with.

Search for the following:

^( ?)( ?)( ?)( ?)( ?)( ?)

(In each pair of parens is a space followed by a question mark.)

Replace-all with:


This is sadly non-general; it relies on there being no more than six levels of indentation. But for my purposes, it works nicely, and is much better than running a series of search-and-replaces.

(I know I said I wasn't going to blog this week, but this is work-related and took only five minutes to write up.)

2 Responses to “Double your indentation with regular expressions!”

  1. Jed

    Ooh, neat; I didn’t know about the “&” operator. That’s much better. Thank you!


Join the Conversation