Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I repeat a Perl Regular Expression until no changes are left?

Tags:

regex

perl

I'm trying to write a simple command line script to fix some whitespace and need to replace occurrences of two spaces with a tab, but only if it appears at the beginning of the line (prefixed only by other tabs.)

I came up with s/^(\t*)  /\1\t/g; which works perfectly if I run through multiple passes, but I don't know enough about perl to know how to loop until the string didn't change, or if there is a regular expression way to handle it.

My only thought was to use a lookbehind but it can't be variable length. I'd be open to a non-regex solution if its short enough to fit into a quick command line script.

For reference, the current perl script is being executed like so:

perl -pe 's/^(\t*)  /$1\t/g'
like image 729
gnarf Avatar asked Mar 28 '11 12:03

gnarf


3 Answers

Check a very similar question.

You could use 1 while s/^(\t*) /$1\t/g; to repeat the pattern until there are no changes left to make.

like image 69
user237419 Avatar answered Sep 20 '22 23:09

user237419


or

perl -pe 's{^(\t*)((  )+)}{$1 . "\t" x (length($2)/length($3))}e'
like image 22
glenn jackman Avatar answered Sep 19 '22 23:09

glenn jackman


Supports mixes of spaces and tabs:

perl -pe'($i,$s)=/^([ \t]*)([.*])/s; $i=~s/  /\t/g; $_="$i$s";'
like image 37
ikegami Avatar answered Sep 20 '22 23:09

ikegami