Regex to change the number of spaces in an indent level

In some regex flavors, you can use a lookbehind:

s/(?<=^ *)  /   /g

In all other flavors, you can reverse the string, use a lookahead (which all flavors support) and reverse again:

 s/  (?= *$)/   /g

Here's another one, instead utilizing \G which has NET, PCRE (C, PHP, R…), Java, Perl and Ruby support:

s/(^|\G) {2}/   /g

\G [...] can match at one of two positions:
✽ The beginning of the string,
✽ The position that immediately follows the end of the previous match.

Source: http://www.rexegg.com/regex-anchors.html#G

We utilize its ability to match at the position that immediately follows the end of the previous match, which in this case will be at the start of a line, followed by 2 whitespaces (OR a previous match following the aforementioned rule).

See example: https://regex101.com/r/qY6dS0/1

Tags:

Regex