My understanding is that /[^\A] +/mg will match globally one or more spaces occurring other than at the beginning of the string or just after newline.
Apparently, I’m wrong.
#!/usr/bin/env perl
use strict;
use warnings;
my $str = " word1 word2\n word3 word4 word5\n";
print "str before = $str\n";
$str =~ s/[^\A] +/ /mg;
print "str after = $str\n";
Output:
str before = word1 word2
word3 word4 word5
str after = word word2 word word word5
The desired output is:
str before = word1 word2
word3 word4 word5
str after = word1 word2
word3 word4 word5
So the leading spaces are preserved in number but multiple spaces occurring after the beginning of each line are reduced to a single space.
I’m not finding what I’m looking for in perldoc perlretut nor perldoc perlre (even after searching through all the instances of “[^” with /\[\^). Many thanks, in advance.
In Perl, the most simple solution is:
s/\S\K +/ /g;See this demo.