lmocsi
lmocsi

Reputation: 1086

negative regex for perl string substitution

I'm trying to shorten all multiple spaces to one space, except for the first occurence of spaces (indentation).

I've found that this code will replace the first occurences:

$_ =~ s/^ +/ /;

So I thought, its negation will do what I want. But it does not:

$_ =~ s/!^ +/ /g;

What am I doing wrong?

Upvotes: 1

Views: 478

Answers (2)

mpapec
mpapec

Reputation: 50647

You can change approach to the regex

s/\S\K +/ /g;

Upvotes: 2

Sobrique
Sobrique

Reputation: 53478

Exclamation mark is not negation in regex. At least, not like that.

What you need is negative lookbehind:

s/(?<!^)\s+/ /g;

Should do the trick.

Upvotes: 1

Related Questions