comp.lang.perl.misc-funny_usage_for_perl_code_on_righ

This is part of The Pile, a partial archive of some open source mailing lists and newsgroups.



From: "Tassilo v. Parseval" <Tassilo.Parseval@post.rwth-aachen.de>
Newsgroups: comp.lang.perl.misc
Subject: Re: Wow! A trivial regexp I can't do!
Date: 3 Oct 2002 17:56:58 GMT

Also sprach Arvin Portlock:

> I thought I knew regular expressions. But when I tried to do this one
> I was amazed I didn't know how.
> 
> I want to replace all occurrences of the string "\n" (that's a backslash
> and an 'n', not a newline) with a newline but only when they occur at
> the end of a string. So I might have the following string:
> 
> "This is a line\n\n\n";
> 
> And I want to replace those last three '\n's with true newlines. I only
> want this to happen when they're at the end of a string though. I know
> how to do it with a while loop, but isn't there some cool way to do it
> with a simple regular expression?
> 
> Obviously $string =~ s/\\n+$/\n/; doesn't do it.

These quantifiers (+ in this case) only work on the character they
follow. But you have two characters, '\' and 'n', so you need to bundle
them:

    $string =~ s!((?:\\n)+)$!"\n" x (length($1)/2)!e;

Whenever you use parens for bundling characters and you don't want
anything captured, make them non-capturing by using ?:. This will make
the whole operation slightly quicker.

Tassilo
-- 
$_=q!",}])(tsuJ[{@"tnirp}3..0}_$;//::niam/s~=)]3[))_$-3(rellac(=_$({
pam{rekcahbus;})(rekcah{lrePbus;})(lreP{rehtonabus;})(rehtona{tsuJbus!;
$_=reverse;s/sub/(reverse"bus").chr(32)/xge;tr~\n~~d;eval;


the rest of The Pile (a partial mailing list archive)

doom@kzsu.stanford.edu