J, 20 bytes
{~[:{~^:_#\-2+_1".,.
,. Each character on a separate row
_1". Convert to numbers, replacing non-numbers with -1
(it becomes one row again)
2+ Add 2.
#\ Prefix lengths (range 1..length)
- Subtract
[:{~^:_ Index into itself as long as it changes the result
{~ Index into the original string
Credit to ngn for the inspiration.
J, 22 bytes
22 bytes
(],,{~1{._1-_1".[)/@|.
This is a port of the Jelly answer.
|. The string backwards, because reduce is right-to-left.
_1".[ The next character as a number (d), -1 if it's not a number,
and a space character produces an empty array.
_1- -1-d
1{. Take 1. If we have a nothing
at this point, that makes it a 0.
, Prepend the next character to the result of the previous call.
{~ Select the character. 0 is the first, _2 is second to last.
], Append the result.
In both solutions the version that TIO uses interprets a single . as the number 0, so the last test fails. Older versions (≤7) seem to work correctly.