user2309694
user2309694

Reputation: 147

Can perl replace multiple substrings with regex?

I have some substring [ aa bb cc ] in a line, like $line = "1 2 a b [ aa bb cc ] c d [ bb cc ] 3 4". And I want to trim all the spaces in these substrings. The following code does not work.

while($line =~ /\[(.*?)\]g/)
{
  $1 =~ s/\s+//g;
}

Can someone help please

Upvotes: 3

Views: 332

Answers (3)

user1919238
user1919238

Reputation:

Your method fails because the match variable $1 is read-only. You can use non-destructive substitution (introduced in Perl 5.16) to avoid that problem:

use warnings;
use strict;

my $line = "[foo bar] [   baz    ]  sproing";
while($line =~ /\[(.*?)\]/g)
{
    my $result = $1 =~ s/\s+//gr;
    print "|$result|\n";
}

Upvotes: 0

perreal
perreal

Reputation: 97918

Another way similar to your attempt:

while($line =~ s/\[([^\]\s]*)\s+/[$1/g) {}

and you don't have to escape the r-square bracket, but it helps vim.

Upvotes: 2

ikegami
ikegami

Reputation: 385546

s{\[(.*?)\]}{
   my $s = $1;
   $s =~ s/\s+//g;
   $s
}eg;

Upvotes: 7

Related Questions