#!/usr/bin/perl
use strict;
use warnings;
my $s = "sad day
Good day
May be Bad Day
";
$s =~ s/\w+ \w+/_/gm;
print $s;
I am trying to substitute all spaces between words with _, but it is not working. What is wrong with that?
#!/usr/bin/perl
use strict;
use warnings;
my $s = "sad day
Good day
May be Bad Day
";
$s =~ s/\w+ \w+/_/gm;
print $s;
I am trying to substitute all spaces between words with _, but it is not working. What is wrong with that?
This pattern replacement is probably the most efficient solution:
$a =~ s/\b \b/_/g;
The substitution replaces an entire word (\w+
) then a space then an other word by an underscore.
There is really no need to replace (or capture for what matters) those words
$a=~s/\b +\b/_/gm;
will replace a word break ( \b
, a zero-width transition between a word and a non word) followed by one or more spaces followed by an other word break, by an underscore. Using \b
ensures that you don't replace a space after or before a new line.
This question wouldn't be complete without an answer involving explicit look-ahead and look-behind assertions:
$s =~ s/(?<=\w) (?=\w+)/_/g
This is effectively the same as the solutions involving the zero-width word-boundary anchor, \b
.
Note that look-ahead regexes can match regexes of any character length, but look-behind regexes have to be of fixed-length (which is why (?<=\w+)
can't be done).