Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to change the number of spaces in an indent level

Tags:

regex

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 is done with spaces, and each indent is two spaces.

You want to change each indent to be three spaces. The simple regex

s/ {2}/   /g

Doesn't work for you, because that changes some non-indent spaces; in this case it changes the two spaces before // Some silly comment into three spaces, which is not desired. (This gets far worse if there are tables or comments aligned at the back end of the line.)

You can't simply use

/^( {2})+/

Because what would you replace it with? I don't know of an easy way to find out how many times a + was matched in a regex, so we have no idea how many altered indents to insert.

You could always go line-by-line and cut off the indents, measure them, build a new indent string, and tack it onto the line, but it would be oh so much simpler if there was a regex.

Is there a regular expression to replace indent levels as described above?

like image 557
So8res Avatar asked Oct 09 '12 20:10

So8res


People also ask

How do you write spaces in regex?

\s stands for “whitespace character”. Again, which characters this actually includes, depends on the regex flavor. In all flavors discussed in this tutorial, it includes [ \t\r\n\f]. That is: \s matches a space, a tab, a carriage return, a line feed, or a form feed.

How define space in regex?

The RegExp \s Metacharacter in JavaScript is used to find the whitespace characters. The whitespace character can be a space/tab/new line/vertical character. It is same as [ \t\n\r].

How do I remove double spacing in C#?

If you need to replace multiple spaces (double spaces) in a string to single space with C# you can use next string method: public string Replace(string oldValue, string newValue)


1 Answers

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
like image 170
John Dvorak Avatar answered Sep 23 '22 03:09

John Dvorak