Regex to change the number of spaces in an indent level

后端 未结 4 2055
天命终不由人
天命终不由人 2021-02-12 23:54

Let\'s say you have some lines that look like this

1  int some_function() {
2    int x = 3;  // Some silly comment

And so on. The indentation i

4条回答
  •  灰色年华
    2021-02-13 00:23

    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

提交回复
热议问题