I've been trying to select all characters except the last word (2 groups where 1 group is everything but the last word and the other group is only the last word)
is what I have so far and I've been stuck.
The second pair of parens contains a continuous string of non-whitespace
\S\+ (also known as a "WORD") preceding the end of the line.
The first pair of parens gobbles everything else except for some whitespace
\s\+. This requirement of ending before some whitespace prevents it from greedily consuming the final WORD.
This ignores the whitespace between groups 1 and 2 and then reinserts a single space in the substitution. But we could also do three captures if you want to preserve the whitespace exactly (e.g. if it has tabs):
Let's make it more readable by using "very magic" mode:
If a line is indented things get a little ugly. Optionally, we could preserve any indentation thusly:
$in the pattern.
/gflag is not required as this pattern matches an entire line...only one substitution possible.
You've specified that you want to use regular expressions and back-references, but, depending on your precise requirements, it's arguably easier to achieve this without using regular expressions.
N.B. I've written
<Space> above, as otherwise the space would be invisible: you should enter an actual space character by pressing your space bar once.
This does roughly the same thing as the first
:substitute command in B Layer's answer and, because it just uses normal-mode commands, should be easy to understand for any Vim user:
:%norm: Run the following series of normal mode commands on every line,
$: Move to end of line; substitute
$if some of your lines end in whitespace,
diw: Delete inner word; substitute
wif you want to move WORDs,
0: Move to beginning of line; substitute
0if you want to preserve indentation,
P: Put the word at the beginning of the line,
a<Space>: Add in a space.
If your file also contains blank lines, you can use
:global to only run the
:normal command on non-blank lines:
Further improvements are possible if you need more sophisticated handling of whitespace.