Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex: replace groups of 4 spaces (from new line until a character) with tabs

Tags:

regex

There are a lot of questions about replacing spaces with tabs on here, however this is the first I've come across which needs to limit the replaces to spaces that are before any characters.

So I start with (?: ) (that's 4 spaces)

Which gives me:

enter image description here

However I only want to match the spaces before any words! So I need to ignore the space's after greedy and accept.

So I try the start line operator ^. Giving me ^(?: )

Which only matches 4 spaces directly prefixed with a ^

enter image description here

So I add + to match many, final regex is ^(?: )+, however that gives me:

enter image description here

which matches all spaces between the start ^ and a character, like I want, however the matches are not in groups of four! The colour block spans the whole line, which is wrong!

I need some Regex pro's to explain to me where I'm going wrong!


EDIT

Should have probably mentioned, I'm not working to any specific regex engine.

I'd rather the solution not use look behinds, but if it has to, it has to.


Here's the text for testing:

                output.parents('.datatable-expanded').droppable({
                    greedy    : true,
                    accept    : '.ui-draggable',
                    tolerance : 'intersect',
                    hoverClass: 'drop-hover',
                    drop: function(e, ui) {
                        self.handleDrop(ui.helper, $(this).parents('tr').prev())
                    },
                });
like image 797
AlexMorley-Finch Avatar asked Dec 02 '25 21:12

AlexMorley-Finch


2 Answers

This one seems to work. It matches the beginning of the string, plus one or more group(s) of 4 spaces.

/\G {4}/g

Example here on regex101

like image 96
tomaoq Avatar answered Dec 04 '25 13:12

tomaoq


This worked in vscode. It halves the number of spaces that start each line.

Find: ^(( )+)\1

Replace with: $1

like image 22
sparebytes Avatar answered Dec 04 '25 13:12

sparebytes