criz
criz

Reputation: 273

Replace an entire string using regex in Perl

I would like it to look something like this.

my $str = 'axxxx';

my $replacement = 'string_begins_with_a';

$str =~ s/^a/$replacement/;

print "$str\n"; #should print 'string_begins_with_a'

Upvotes: 2

Views: 306

Answers (2)

Arunesh Singh
Arunesh Singh

Reputation: 3535

Match the whole string with a ^a.* regex and then replace it using your replacement string.

$str =~ s/^a.*/$replacement/;
print "$str\n"; # would print 'string_begins_with_a'

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626806

You just need to consume the rest of the line by adding .* after a:

my $str = 'axxxx';
my $replacement = 'string_begins_with_a';
$str =~ s/^a.*/$replacement/;
print "$str\n"; #prints 'string_begins_with_a'

Or, you may just check if $str starts with a, and then assign the $replacement value to it:

$str = ($str =~ /^a/) ? $replacement : $str;

or just

if ($str =~ /^a/) {
    $str = $replacement;
}

Upvotes: 2

Related Questions