简体   繁体   中英

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'

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;
}

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM