Replacing spaces with underscores (ignore spaces that beginning or end of the string)

I got below code that able to replace spaces to underscore.

Code:

use strict;
use warnings;    

my $subject ="FD 2000k";

print "Before - $subject\n";
#Result : Before - FD 2000k    
$subject =~ tr/ /_/;

print "After - $subject\n";
#Result : After - FD_2000k

However, if the $subject consists of space at the end of FD 2000k and the result will be After - FD_2000K_. Refer to below code.

Code:

use strict;
use warnings;  

#Note: Behind 2000k got space
my $subject ="FD 2000k ";

print "Before - $subject\n";
#Result : Before - FD 2000k    
$subject =~ tr/ /_/;

print "After - $subject\n";
#Result : After - FD_2000k_

Anyone know how to ignore the spaces that appear on the beginning or end of the string?

Expected result : Ignore the spaces that before or after string, just replace the spaces that in the "middle" of the string. Result should be FD_2000k instead of FD_2000k_

Thanks!

Upvotes: 0

Views: 1238

Answers (1)

Toto
Toto

Reputation: 91518

Use the substitution:

$subject =~  s/(?<=\w)\s(?=\w)/_/g;

This will replace spaces only if they are preceeded and followed by a word character.

You could also use:

 $subject =~  s/(?<!^)\s(?!$)/_/g;

This will replace spaces only if they aren't at the begining or at the end of the string.

Upvotes: 3

Related Questions