clankill3r
clankill3r

Reputation: 9543

change order of columns with regex

I have columns like:

9   100 100 0
            10
            20
            30
        110 0
            10
            20
            30
        120 0
            10
            20
            30
    120 100 0
            10
            20
            30

I want to reverse the order of the columns like:

\3\2\1\0

This is how I try to get one column:

(\t?|\d+)

It makes sense to me but it aint working, does anyone see the mistake?

After that it assume it is repeating:

(\t?|\d+)(\t?|\d+)(\t?|\d+)(\t?|\d+)

Followed with:

\3\2\1\0

Can someone help me with fixing it?

Upvotes: 3

Views: 351

Answers (2)

Francis Gagnon
Francis Gagnon

Reputation: 3675

Your sample text with the columns doesn't contain any tabs. So here is a solution that allows for spaces and tabs to be used to delimit columns:

^(\d*)([ \t]+)(\d*)([ \t]+)(\d*)([ \t]+)(\d+)$

This next regex does the same thing as the one above but is a bit more efficient. It is also less easy to read.

^[ \t]*(?:(\d+)([ \t]+))?(?:(\d+)([ \t]+))?(?:(\d+)([ \t]+))?(\d+)$

It has 7 capture groups. Groups 1,3,5,7 are the column values and groups 2,4,6 are the column separators.

Your replace expression should be something like this, which essentially reverses everything:

\7\6\5\4\3\2\1

Should you want to fix the separators and use tabs instead, you could perhaps use something like this as a replace expression:

\7\t\5\t\3\t\1

Upvotes: 0

Klas Lindbäck
Klas Lindbäck

Reputation: 33273

Try

^(\d*)\t(\d*\t)(\d*\t)(\d*)$

and replace it with:

\4\t\3\2\1

(Untested, but it feels right)

If there is other whitespace than tabs you may need to revise the regex accordingly.

Upvotes: 4

Related Questions