Tree
Tree

Reputation: 10362

What is wrong with this substitution?

#!/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?

Upvotes: 2

Views: 162

Answers (3)

Zaid
Zaid

Reputation: 37156

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).

Upvotes: 2

mirod
mirod

Reputation: 16171

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.

Upvotes: 5

amphetamachine
amphetamachine

Reputation: 30651

This pattern replacement is probably the most efficient solution:

$a =~ s/\b \b/_/g;

Upvotes: 3

Related Questions