[Cialug] Regex Question

Todd Walton tdwalton at gmail.com
Fri Oct 12 13:30:46 UTC 2018


I somewhat frequently run into this specific type of problem... Let's say I
have this text:

group
    something  -->  blah
  another   -->           yes

I want to line these up all pretty like. I want there to be, say, four
spaces at the start of the something and the another lines, then the word,
then a number of spaces that varies depending on the length of the first
word, and then -->, a space, and the final word. Like this:

group
    something --> blah
    another   --> yes

If your email reader can handle it, I typed those in in fixed width font,
for visual clarity. The problem is that no regex I've ever seen has any
facility for length. I could determine that there should be 14 total
characters before the -->, and then do this:

search: ^\s+([a-z]{9})\s+-->
replace: \s\s\s\s\1 -->

That would replace the something line. And then I would reduce the digit by
1 and add 1 space before the -->. Then repeat. Then repeat. That's what I
usually do. But I wish I could somehow say "four spaces, then the captured
backreference, then a number of spaces equal to 10 minus the captured
backreference's length". I know that's a mental mouthful, but hopefully you
can see what I'm getting at. One would think that horizontal tabs were
invented for this very thing, but they don't always line up right,
especially if the variability in word length is high, and also I don't want
tab characters in the result.

Y'all ever run into this kind of problem?

--
Todd


More information about the Cialug mailing list