« Temporary Self-Imposed Netlessness Syndrome | Main | No California same-sex weddings for now »

Double your indentation with regular expressions!

| 2 Comments

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:

\1\1\2\2\3\3\4\4\5\5\6\6

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 Comments

s/^ */&&/


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


Post a comment