Regex to change the number of spaces in an indent level

后端 未结 4 2063
天命终不由人
天命终不由人 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:33

    You can try this:

    ^(\s{2})|((?<=\n(\s)+))(\s{2})
    

    Breakdown:

    ^(\s{2})  = Searches for two spaces at the beginning of the line
    ((?<=\n(\s)+))(\s{2}) = Searches for two spaces
        but only if a new line followed by any number of spaces is in front of it.
        (This prevents two spaces within the line being replaced)
    

    I'm not completely familiar with perl, but I would try this to see if it work:

    s/^(\s{2})|((?<=\n(\s)+))(\s{2})/\s\s\s/g
    

    As @Jan pointed out, there can be other non-space whitespace characters. If that is an issue, try this:

    s/^( {2})|((?<=\n( )+))( {2})/   /g
    

提交回复
热议问题