Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl: How to replace only matched part of string?

Tags:

string

regex

perl

I have a string foo_bar_not_needed_string_part_123. Now in this string I want to remove not_needed_string_part only when foo_ is followed by bar.

I used the below regex:

my $str = "foo_bar_not_needed_string_part_123";

say $str if $str =~ s/foo_(?=bar)bar_(.*?)_\d+//;

But it removed the whole string and just prints a newline.

So, what I need is to remove only the matched (.*?) part. So, that the output is

foo_bar__123.
like image 927
RanRag Avatar asked Sep 16 '12 08:09

RanRag


2 Answers

There's another way, and it's quite simple:

my $str = "foo_bar_not_needed_string_part_123";
$str =~ s/(?<=foo_bar_)\D+//gi;
print $str;

The trick is to use lookbehind check anchor, and replace all non-digit symbols that follow this anchor (not a symbol). Basically, with this pattern you match only the symbols you need to be removed, hence no need for capturing groups.

As a sidenote, in the original regex (?=bar)bar construct is redundant. The first part (lookahead) will match only if some position is followed by 'bar' - but that's exactly what's checked with non-lookahead part of the pattern.

like image 87
raina77ow Avatar answered Nov 09 '22 04:11

raina77ow


You can capture the parts you do not want to remove:

my $str = "foo_bar_not_needed_string_part_123";
$str =~ s/(foo_bar_).*?(_\d+)/$1$2/;
print $str;
like image 45
tanguy Avatar answered Nov 09 '22 04:11

tanguy