tags:

views:

110

answers:

4

In perl, if I have a string $str and a pattern saved in $pat and I want to replace what is saved in $pat with 'nothing' only if $pat appears at the end of $str, how would the regular expression look like? I tried different versions of this - s/\$pat$//

That, and all variations( s/$pat$//, s/\${pat}$//, s/${pat}$//) are not working :|

my $str = " aaa.::aa*bb/bb*cc:1/cc\n xxx.::xx*yy/yy*zz:1/xx\n";

my $pat = "xxx.::xx*yy/yy*zz:1/xx";

$str =~ s/$pat\n$//;

print $str;
+1  A: 

You should provide some more code. The following works just fine for me:

my $pat = 'foo';
my $str = 'barbarfoo';

$str =~ s/.+\Q$pat\E$/nothing/;

print $str, "\n";

Edit: After receiving a helpful comment, I added quoting with \Q and \E to the above regular expression.

innaM
I have '/' in both $pat and $str. Sorry for not mentioning this earlier.$pat = 'some/foo:more/foo'; $str = "some/str:more/str\nsome/foo:more/foo";
Wikidkaka
Thanks for letting me/us know. I modified my answer accordingly.
innaM
A: 

this works for me:

$str =~ s/$pat$//;
spudly
A: 

In addition to my comment this is what "works" for me:

my $pat = 'this';
my $string = 'not this but this';
$string =~ s/$pat$//;
say $string;

# outputs "not this but"


Update using your new example

What u need is quotemeta for it to work:

my $str = " aaa.::aa*bb/bb*cc:1/cc\n xxx.::xx*yy/yy*zz:1/xx\n";
my $pat = quotemeta "xxx.::xx*yy/yy*zz:1/xx";

$str =~ s/$pat\n$//;

print $str;

# now prints : aaa.::aa*bb/bb*cc:1/cc\n

/I3az/

draegtun
+2  A: 

If your pattern contains special regex characters, you need to tell Perl to treat them as literals -- for example, by using quotemeta.

my $str = " aaa.::aa*bb/bb*cc:1/cc\n xxx.::xx*yy/yy*zz:1/xx\n";
my $pat =                           "xxx.::xx*yy/yy*zz:1/xx";

$pat = quotemeta $pat;
$str =~ s/$pat$/NOTHING/;

print $str;

If you don't want to modify $pat using quotemeta, you can also use the \Q and \E escape characters, which apply quotemeta to the enclosed portion of the pattern.

$str =~ s/\Q$pat\E$/NOTHING/;
FM